<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增内文生产单</div>
            <div v-else-if="route.query?.copy">复制内文生产单</div>
            <div v-else-if="route.query?.info">
              内文生产单详情
              <el-tag>{{ form.produceNo }}</el-tag>
            </div>
            <div v-else>
              编辑内文生产单
              <el-tag>{{ form.produceNo }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <!--  -->
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <!-- <el-button type="primary" @click="editProduceInfo">修 改</el-button> -->
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              ref="userRef"
              label-width="120px"
            >
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="下单日期" prop="submitDate">
                                        <el-date-picker style="width: 100%; " v-model="form.submitDate"
                                            value-format="YYYY-MM-DD " type="date" placeholder="请选择日期" />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="16">
                  <el-form-item label="产品名称" prop="productName">
                    <el-input
                      v-model="form.productName"
                      readonly
                      :disabled="flag"
                      @click="handleAddProduceProductList"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <!-- @change="changePubNo" -->
                  <el-form-item label="出版编号" prop="pubNo">
                    <el-input
                      :disabled="flag"
                      v-model="form.pubNo"
                      :validate-event="false"
                      maxlength="20"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item
                                        label="出版编号"
                                        :prop="form.isNew != '1' ? 'pubNo' : ''"
                                    >
                                        <el-input
                                            v-model="form.pubNo"
                                            :validate-event="false"
                                            :readonly="form.isNew == '1'"
                                            :placeholder="
                                                form.isNew == 1 ? '自动生成' : '请输入出版编码'
                                            "
                                            maxlength="20"
                                        />
                                    </el-form-item>
                                </el-col> -->
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="新/旧版" prop="isNew">
                    <el-select
                      style="width: 100%"
                      v-model="form.isNew"
                      placeholder="请选择"
                      :disabled="flag"
                    >
                      <el-option
                        v-for="item in ems_produce_is_new"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="印刷次数" prop="printNum">
                    <el-input
                      :disabled="flag"
                      v-model="form.printNum"
                      readonly
                      type="number"
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="订单数量" prop="orderCount">
                    <el-input
                      @mousewheel.prevent
                      :disabled="flag"
                      v-model="form.orderCount"
                      @change="changeOrderCount"
                      type="number"
                      placeholder="请输入订单数量"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="下单日期" prop="submitDate">
                    <el-date-picker
                      :disabled="flag"
                      style="width: 100%"
                      v-model="form.submitDate"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="打包方式" prop="packWay">
                    <!-- <el-input
                                            v-model="form.packWay"
                                            placeholder="请输入打包方式"
                                        /> -->
                    <el-select
                      clearable
                      style="width: 100%"
                      v-model="form.packWay"
                      placeholder="请选择"
                      :disabled="flag"
                    >
                      <el-option
                        v-for="item in ems_order_pack_way"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="定价" prop="fixPrice">
                    <el-input
                      clearable
                      :disabled="flag"
                      v-model="form.fixPrice"
                      type="number"
                      placeholder="请输入定价"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="加急交货日期" prop="urgentDate">
                                        <el-date-picker style="width: 100%; " v-model="form.urgentDate"
                                            format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm"
                                            type="datetime" placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                            </el-row> -->

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="交货日期" prop="deliverDate">
                    <el-date-picker
                      :disabled="flag"
                      style="width: 100%"
                      v-model="form.deliverDate"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="包内数量" prop="packInNum">
                    <el-input
                      :disabled="flag"
                      v-model="form.packInNum"
                      type="number"
                      placeholder="请输入包内数量"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="印次" prop="printNo">
                    <el-input
                      :disabled="flag"
                      v-model="form.printNo"
                      placeholder="请输入印次"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="文件日期" prop="fileDate">
                    <el-date-picker
                      :disabled="flag"
                      style="width: 100%"
                      v-model="form.fileDate"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="打包要求" prop="packageRequire">
                    <el-autocomplete
                      v-model="form.packageRequire"
                      :fetch-suggestions="querySearch"
                      clearable
                      :disabled="flag"
                      style="width: 100%"
                      class="inline-input w-50"
                      placeholder="请选择或者输入"
                      @select="handleSelect"
                    />
                    <!-- <el-select
                                            style="width: 100%"
                                            v-model="form.packageRequire"
                                            placeholder="请选择"
                                        >
                                            <el-option
                                                v-for="item in ems_produce_package_require"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select> -->
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="书号" prop="bookNo">
                    <!--:disabled="flag"-->
                    <el-input
                      clearable
                      v-model="form.bookNo"
                      placeholder="自动带出"
                      :disabled="flag"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="封面生产单编码" prop="produceCoveringNo">
                                        <el-input
                                            readonly
                                            :disabled="flag"
                                            v-model="form.produceCoveringNo"
                                            placeholder="请选择"
                                            @click="handleAddProduceCovingList"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="送货单位" prop="customName">
                    <el-input
                      readonly
                      :disabled="flag"
                      v-model="form.customName"
                      placeholder="请选择"
                      @click="handleSelectCustomName"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出版社" prop="publishingHouse">
                    <el-input
                      clearable
                      :disabled="flag"
                      v-model="form.publishingHouse"
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="车间" prop="workshopId">
                    <el-select
                      :disabled="flag"
                      @change="changeWorkShopName"
                      style="width: 100%"
                      v-model="form.workshopId"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in ems_workshop"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="合印生产单" prop="mergePrintCode">
                    <el-input
                      v-model="form.mergePrintCode"
                      readonly
                      :disabled="flag"
                      @click="handleJointPrint"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="发货品种" prop="shipmentType">
                    <el-input
                      :disabled="flag"
                      v-model="form.shipmentType"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="版材备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="产品信息" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">产品信息</span>
          </template>
          <div class="order-form">
            <!-- <el-button
                            size="small"
                            type="primary"
                            style="margin-bottom: 5px"
                            v-if="!route.query.info"
                            @click="handleAddProduceProductList"
                            >选择产品</el-button
                        > -->
            <el-form
              :model="data"
              ref="produceProductListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                class="myTable"
                :data="data.produceProductList"
                border
                :header-cell-class-name="must"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />

                <el-table-column
                  label="订单数量"
                  width="120"
                  prop="produceCount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'produceProductList.' + scope.$index + '.produceCount'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '订单数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <!-- @mousewheel.native.prevent -->
                      <el-input
                        @mousewheel.prevent
                        type="number"
                        @blur="changeProduceCount(scope.row)"
                        v-model="scope.row.produceCount"
                        placeholder="请输入订单数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                                    label="书刊编码"
                                    min-width="120"
                                    prop="bookCode"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="书刊名称"
                                    min-width="160"
                                    prop="bookName"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="是否做版"
                                    prop="newPast"
                                    min-width="120"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                            :prop="
                                                'produceProductList.' + scope.$index + '.newPast'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '是否做版',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                clearable
                                                style="width: 100%"
                                                v-model="scope.row.newPast"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in ems_produce_new_past"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="书刊编码"
                                    min-width="120"
                                    prop="bookNo"
                                    align="center"
                                >
                                </el-table-column> -->
                <el-table-column
                  label="品种"
                  prop="breedType"
                  width="120"
                  align="center"
                >
                  <!-- <template #default="scope">
                                        <dict-tag
                                            :options="ems_order_breed_type"
                                            :value="scope.row.breedType"
                                        />
                                    </template> -->
                </el-table-column>

                <el-table-column
                  label="装订方式"
                  width="140"
                  prop="bindingMode"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_binding_mode"
                      :value="scope.row.bindingMode"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="开本数"
                  width="100"
                  prop="bookSize"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'produceProductList.' + scope.$index + '.bookSize'"
                      :rules="[
                        {
                          required: true,
                          message: '开本数',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.bookSize"
                        placeholder="请选择开本数"
                      >
                        <el-option
                          v-for="item in ems_produce_book_size"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="组成"
                  width="100"
                  prop="composition"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_make_up"
                      :value="scope.row.composition"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="详细信息"
                  min-width="120"
                  prop="detail"
                  align="center"
                >
                </el-table-column> -->
                <el-table-column
                  label="详细信息"
                  min-width="720"
                  prop="detail"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.detail"
                        type="textarea"
                        placeholder="请输入详细信息"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="贴数信息"
                  width="200"
                  prop="piece"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.piece"
                      placeholder="贴数信息"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印张"
                  width="100"
                  prop="sheet"
                  align="center"
                >
                  <!-- <template #default="scope">
                    <el-form-item
                                            :prop="'produceProductList.' + scope.$index + '.sheet'"
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '印张',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-input
                                                type="number"
                                                @blur="changeSheet(scope.row, scope.$index)"
                                                v-model.number="scope.row.sheet"
                                                placeholder="自动计算"
                                            ></el-input>
                                        </el-form-item>
                  </template> -->
                </el-table-column>
                <el-table-column
                  label="印色"
                  min-width="100"
                  prop="printColor"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_print_color"
                      :value="scope.row.printColor"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="颜色"
                  width="120"
                  prop="color"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'produceProductList.' + scope.$index + '.color'"
                      :rules="[
                        {
                          required: true,
                          message: '颜色',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        clearable
                        style="width: 100%"
                        v-model="scope.row.color"
                        placeholder="请选择颜色"
                      >
                        <el-option
                          v-for="item in ems_produce_color"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="用纸尺寸"
                  prop="paperSize"
                  min-width="135"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'produceProductList.' + scope.$index + '.paperSize'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '用纸尺寸',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.paperSize"
                        placeholder="请选择用纸尺寸"
                      >
                        <el-option
                          v-for="item in ems_produce_paper_size"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="成品尺寸(mm)"
                  width="130"
                  prop="finishSize"
                  align="center"
                >
                  <template #default="scope">
                    <!-- <dict-tag
                                            :options="ems_produce_finish_size"
                                            :value="scope.row.finishSize"
                                        /> -->
                    <el-select
                      style="width: 100%"
                      v-model="scope.row.finishSize"
                      placeholder="请输入成品尺寸"
                      @change="changeFinishSize(scope.row, scope.$index)"
                      :disabled="flag"
                    >
                      <el-option
                        v-for="item in ems_produce_finish_size"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="版材尺寸"
                  min-width="125"
                  prop="sheetSize"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'produceProductList.' + scope.$index + '.sheetSize'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '版材尺寸',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-select
                        @blur="changeBCCC(scope.row, scope.$index)"
                        clearable
                        style="width: 100%"
                        v-model="scope.row.sheetSize"
                        placeholder="请选择版材尺寸"
                      >
                        <el-option
                          v-for="item in ems_machine_info_size"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸型"
                  width="120"
                  prop="paperType"
                  align="center"
                >
                  <!-- <template #default="scope">
                                        <dict-tag
                                            :options="mes_paper_type"
                                            :value="scope.row.paperType"
                                        />
                                    </template> -->
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.paperType"
                        placeholder="请选择纸型"
                        :disabled="flag"
                      >
                        <el-option
                          v-for="item in mes_paper_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="纸张编码"
                  min-width="160"
                  prop="paperNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'produceProductList.' + scope.$index + '.paperNo'"
                      :rules="[
                        {
                          required: true,
                          message: '纸张编码',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.paperNo"
                        readonly
                        @click="openPaperDialog(scope.row, scope.$index)"
                        placeholder="请选择纸张编码"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸张名称"
                  min-width="160"
                  prop="paperName"
                  align="center"
                />

                <!-- <el-table-column label="内文贴数" width="120" prop="textPlateCount" align="center">
                                    <template #default="scope">
                                        <el-form-item>
                                            <el-input v-model="scope.row.textPlateCount"
                                                @change="changeTextPlateCount(scope.row, scope.$index)"
                                                placeholder=" 请输入内文贴数"></el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="用版数量"
                  width="100"
                  prop="boardsCount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        type="number"
                        @mousewheel.prevent
                        v-model="scope.row.boardsCount"
                        placeholder="请输入用版数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="出版编码"
                  width="120"
                  prop="pubNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.pubNo"
                        placeholder="出版编码"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="清样编号"
                  min-width="120"
                  prop="sampleNo"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.sampleNo"
                        placeholder="请输入清样编号"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="烤版"
                  width="100"
                  prop="kaoban"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-select
                        style="width: 100%"
                        v-model="scope.row.kaoban"
                        placeholder="请选择烤版"
                      >
                        <el-option label="是" value="1" />
                        <el-option label="否" value="2" />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="产品序列号"
                  v-if="route.query?.id && !copy"
                  min-width="120"
                  prop="productNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="相关封面生产单"
                  min-width="150"
                  prop="produceNos"
                  align="center"
                >
                  <template #default="scope">
                    <el-tag
                      v-for="(tag, index) in scope.row.produceNos?.split(',')"
                      :key="tag"
                      :closable="!route.query?.info"
                      :disable-transitions="false"
                      @close="handleClose(scope.row, tag, index)"
                    >
                      {{ tag }}
                    </el-tag>
                    <div>
                      <el-button
                        class="button-new-tag"
                        size="small"
                        type="primary"
                        circle
                        @click="showCover(scope.row)"
                      >
                        +
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!route.query.info"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
          <!-- <h4>备注</h4>
                    <el-input v-model="form.remark1" type="textarea" placeholder="请输入内容"></el-input> -->
        </el-collapse-item>
        <el-collapse-item disabled title="纸张信息" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">纸张信息</span>
          </template>
          <div class="order-form">
            <el-form
              :model="data"
              ref="producePaperListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.producePaperList"
                ref="producePaperListRef"
                border
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <!-- <el-table-column
                                    label="纸张名称"
                                    min-width="120"
                                    prop="paperNo"
                                    align="center"
                                /> -->
                <el-table-column
                  label="纸张类型"
                  prop="type"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_material"
                      :value="scope.row.type"
                    />
                    <!-- <el-form-item :prop="'producePaperList.' + scope.$index + '.type'"
                                            :rules="[{ required: true, message: '请输入', trigger: 'change' }]">
                                            <el-select clearable style="width:100%" v-model="scope.row.type"
                                                placeholder="请选择纸张类型">
                                                <el-option v-for="item in mes_paper_material" :key="item.value"
                                                    :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸张名称"
                  min-width="160"
                  prop="paperName"
                  align="center"
                />
                <el-table-column
                  label="纸型"
                  min-width="120"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_type"
                      :value="scope.row.paperType"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="品种" min-width="120" prop="breed" align="center">
                                    <template #default="scope">
                                        <dict-tag :options="ems_order_breed_type" :value="scope.row.breed" />
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="定量"
                  min-width="80"
                  prop="weight"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="规格"
                  min-width="120"
                  prop="specifications"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_specs"
                      :value="scope.row.specifications"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="幅宽(mm)"
                  min-width="120"
                  prop="length"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="宽度(mm)"
                                    min-width="100"
                                    prop="width"
                                    align="center"
                                ></el-table-column> -->
                <el-table-column
                  label="单位"
                  min-width="80"
                  prop="unit"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_unit"
                      :value="scope.row.unit"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="库存数量"
                  min-width="110"
                  prop="amount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="数量"
                  min-width="110"
                  prop="reamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="品牌"
                  min-width="120"
                  prop="brand"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_brand"
                      :value="scope.row.brand"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="裁切尺寸"
                  width="120"
                  prop="size"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        v-model="scope.row.size"
                        placeholder="请输入裁切尺寸"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸张编码"
                  min-width="120"
                  prop="paperNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  v-if="route.query?.id && !copy"
                  label="纸张序列号"
                  min-width="120"
                  prop="paperProduceNo"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="加权单价"
                                    min-width="120"
                                    prop="unitPrice"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="金额"
                                    width="120"
                                    prop="price"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item>
                                            <el-input
                                                v-model="scope.row.price"
                                                placeholder="自动计算"
                                            ></el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->

                <!-- <el-table-column
                  label="操作"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeletePaper(scope.row,scope.$index)"
                    ></el-button>
                  </template>
                </el-table-column> -->
              </el-table>
            </el-form>
          </div>
          <!-- <h4>备注</h4>
                    <el-input v-model="form.remark2" type="textarea" placeholder="请输入内容"></el-input> -->
        </el-collapse-item>
        <el-collapse-item disabled title="不配套图书管理" name="4">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">不配套图书管理</span>
          </template>
          <div class="order-form">
            <div style="overflow-x: scroll">
              <table
                border="2"
                v-if="listBPT.length > 0"
                cellspacing="0"
                cellpadding="6"
              >
                <tr>
                  <td class="text" rowspan="2" style="width: 60px">
                    不配套图书
                  </td>
                  <td class="text" style="width: 300px">单号</td>
                  <td class="text" style="width: 100px">品种</td>
                  <td
                    class="text"
                    v-for="(item, index) in listBPT"
                    :key="index"
                    width="160"
                  >
                    {{ item.name }}
                  </td>
                </tr>
                <tr>
                  <td class="text">
                    <el-input
                      style="width: 300px"
                      :disabled="flag"
                      v-model="bookCode"
                    ></el-input>
                  </td>
                  <td class="text" style="width: 100px">数量</td>
                  <td
                    class="text"
                    v-for="(item, index) in listBPT"
                    :key="index"
                  >
                    <el-input
                      :disabled="flag"
                      style="width: 160px"
                      type="number"
                      @mousewheel.prevent
                      v-model="item.val"
                    ></el-input>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title=" 印刷管理" name="5">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">印刷管理</span>
          </template>
          <div>
            <el-button
              size="small"
              type="primary"
              :disabled="multiple"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
              @click="handleHalf"
            >
              半代
            </el-button>
            <el-button
              size="small"
              type="primary"
              :disabled="multiple"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
              @click="handleWhole"
            >
              整代
            </el-button>
            <el-button
              size="small"
              type="primary"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
              @click="handleHalfAuto"
            >
              一键半代
            </el-button>
            <el-button
              size="small"
              type="primary"
              :disabled="multiple"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
              @click="handleDIY"
            >
              自定义半代
            </el-button>
          </div>
          <div class="order-form">
            <el-form :model="data" ref="producePrintListForm" class="data-form">
              <el-table
                :data="data.producePrintList"
                row-key="printId"
                ref="producePrintListRef"
                border
                :header-cell-class-name="mustPrint"
                :show-checkbox="false"
                @selection-change="handlePrintChange"
                :selectable="true"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />

                <!-- <el-table-column
                                    label="书刊编码"
                                    min-width="120"
                                    prop="bookNo"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="书刊名称"
                                    min-width="160"
                                    prop="bookName"
                                    align="center"
                                >
                                </el-table-column> -->
                <el-table-column
                  label="品种"
                  prop="breed"
                  min-width="160"
                  align="center"
                >
                  <!-- <template #default="scope">
                                        <dict-tag
                                            :options="ems_order_breed_type"
                                            :value="scope.row.breed"
                                        />
                                    </template> -->
                </el-table-column>
                <el-table-column
                  label="组成"
                  min-width="160"
                  prop="composition"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_order_make_up"
                      :value="scope.row.composition"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="印张"
                  width="100"
                  prop="sheet"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="贴标"
                  width="120"
                  prop="labeling"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      v-if="scope.row.status"
                      :prop="'producePrintList.' + scope.$index + '.labeling'"
                      :rules="[
                        {
                          required: true,
                          message: '贴标',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        type="number"
                        @mousewheel.prevent
                        :disabled="flag"
                        @change="changeLabeling"
                        :onkeypress="onlyInteger"
                        v-model="scope.row.labeling"
                        placeholder="请输入贴标"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印数"
                  width="120"
                  prop="printAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="用纸令数"
                  width="120"
                  prop="reamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="损耗系数"
                  width="100"
                  prop="lossCoefficient"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        @blur="changeLossCoefficient(scope.row, scope.$index)"
                        v-model="scope.row.lossCoefficient"
                        placeholder="请输入损耗系数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="损耗令数"
                  width="120"
                  prop="lossReam"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="用纸总令数"
                  width="120"
                  prop="totalReamAmount"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="吨位系数"
                  width="120"
                  prop="tonnageCoefficient"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        @blur="
                          handleTonnageCoefficient(scope.row, scope.$index)
                        "
                        v-model="scope.row.tonnageCoefficient"
                        placeholder="请输入吨位系数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="印刷方式"
                  prop="printType"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_package"
                      :value="scope.row.printType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="轮转吨数"
                  width="120"
                  prop="rotateTon"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'producePrintList.' + scope.$index + '.rotateTon'"
                      :rules="
                        scope.row.printType == 2
                          ? [
                              {
                                required: true,
                                message: '轮转吨数',
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        v-model="scope.row.rotateTon"
                        placeholder="请输入轮转吨数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="版材尺寸"
                  prop="sheetSize"
                  min-width="125"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_machine_info_size"
                      :value="scope.row.sheetSize"
                    />
                    <!-- <el-form-item
                                            :prop="
                                                'producePrintList.' + scope.$index + '.sheetSize'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '版材尺寸',
                                                    trigger: 'change',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                :disabled="flag"
                                                clearable
                                                style="width: 100%"
                                                v-model="scope.row.sheetSize"
                                                placeholder="请选择版材尺寸"
                                            >
                                                <el-option
                                                    v-for="item in ems_machine_info_size"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item> -->
                  </template>
                </el-table-column>
                <el-table-column
                  label="另行加放"
                  width="120"
                  prop="lxjf"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        @change="changeLxjf"
                        v-model="scope.row.lxjf"
                        placeholder="请输入另行加放"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="成品尺寸"
                  width="120"
                  prop="finishSize"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="ems_produce_finish_size"
                      :value="scope.row.finishSize"
                    />
                    <!-- <el-form-item
                                            :prop="
                                                'producePrintList.' + scope.$index + '.finishSize'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '成品尺寸',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-select
                                                clearable
                                                style="width: 100%"
                                                v-model="scope.row.finishSize"
                                                placeholder="请选择成品尺寸"
                                            >
                                                <el-option
                                                    v-for="item in ems_produce_finish_size"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                />
                                            </el-select>
                                        </el-form-item> -->
                  </template>
                </el-table-column>

                <el-table-column
                  label="工艺"
                  min-width="160"
                  prop="technologyId"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="
                        'producePrintList.' + scope.$index + '.technologyId'
                      "
                      :rules="[
                        {
                          required: true,
                          message: '工艺',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        :disabled="flag"
                        clearable
                        style="width: 100%"
                        v-model="scope.row.technologyId"
                        placeholder="请选择工艺"
                      >
                        <el-option
                          v-for="item in technologyList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                                    label="白纸裁切"
                                    min-width="120"
                                    prop="whitecuttingMachine"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-button
                                            link
                                            :disabled="flag"
                                            type="primary"
                                            @click="
                                                handlePrintWorkBranch(
                                                    scope.row,
                                                    scope.$index,
                                                    '5',
                                                    'whitecuttingMachine'
                                                )
                                            "
                                        >
                                            {{ scope.row.whitecuttingMachine }}
                                        </el-button>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="印刷"
                  min-width="120"
                  prop="printMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '2',
                          'printMachine'
                        )
                      "
                    >
                      {{ scope.row.printMachine }}
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  label="半代裁切"
                  min-width="120"
                  prop="whitecuttingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '6',
                          'whitecuttingMachine'
                        )
                      "
                    >
                      {{ scope.row.whitecuttingMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="封面裁切"
                  min-width="120"
                  prop="covercuttingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '6',
                          'covercuttingMachine'
                        )
                      "
                    >
                      {{ scope.row.covercuttingMachine }}
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  label="覆膜"
                  min-width="120"
                  prop="coveringMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '7',
                          'coveringMachine'
                        )
                      "
                    >
                      {{ scope.row.coveringMachine }}
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  label="折页"
                  min-width="120"
                  prop="foldMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '4',
                          'foldMachine'
                        )
                      "
                    >
                      {{ scope.row.foldMachine }}
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column
                  label="装订"
                  min-width="120"
                  prop="bindingMachine"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="
                        handlePrintWorkBranch(
                          scope.row,
                          scope.$index,
                          '3',
                          'bindingMachine'
                        )
                      "
                    >
                      {{ scope.row.bindingMachine }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="纸张规格"
                  width="120"
                  prop="paperSpecifications"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_specs"
                      :value="scope.row.paperSpecifications"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="下单印数"
                  width="120"
                  prop="orderPrintCount"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        type="number"
                        @mousewheel.prevent
                        v-model="scope.row.orderPrintCount"
                        placeholder="请输入下单印数"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="纸型"
                  width="120"
                  prop="paperType"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_type"
                      :value="scope.row.paperType"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="定量"
                  min-width="120"
                  prop="weight"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="幅宽"
                  width="120"
                  prop="clothWidth"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="品牌"
                  width="120"
                  prop="brand"
                  align="center"
                >
                  <template #default="scope">
                    <dict-tag
                      :style="{
                        color:
                          scope.row.status == 1 && scope.row.printType == 2
                            ? '#5A9CF8'
                            : '',
                      }"
                      :disabled="flag"
                      @click="clickFn(scope.row, scope.$index)"
                      :options="mes_paper_brand"
                      :value="scope.row.brand"
                    ></dict-tag>
                  </template>
                </el-table-column>
                <!--                                <el-table-column-->
                <!--                                    label="分配机台"-->
                <!--                                    width="120"-->
                <!--                                    prop="machineName"-->
                <!--                                    align="center"-->
                <!--                                >-->
                <!--                                </el-table-column>-->
                <!--                                <el-table-column-->
                <!--                                    label="分配车间"-->
                <!--                                    width="120"-->
                <!--                                    prop="workshopName"-->
                <!--                                    align="center"-->
                <!--                                >-->
                <!--                                </el-table-column>-->
                <el-table-column
                  v-if="route.query?.id && !copy"
                  label="印刷序列号"
                  min-width="120"
                  prop="printProduceNo"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="备注"
                  width="120"
                  prop="remark"
                  fixed="right"
                  align="center"
                >
                  <template #default="scope">
                    <el-form-item>
                      <el-input
                        :disabled="flag"
                        v-model="scope.row.remark"
                        placeholder="请输入备注"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  v-if="!route.query.info"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      v-if="scope.row.status"
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeleteTs(scope.row)"
                    ></el-button>
                    <el-button
                      v-if="scope.row.printType == '1' && !scope.row.status"
                      link
                      type="primary"
                      @click="handleQk(scope.row, scope.$index)"
                      >全开
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
          <h4>印刷备注</h4>
          <el-input
            v-model="form.remark3"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-collapse-item>
        <el-collapse-item disabled title="贴数管理" name="6">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">贴数管理</span>
          </template>
          <div>
            <el-button
              size="small"
              @click="handleProducePiece"
              type="primary"
              style="margin-bottom: 10px"
              v-if="!route.query.info"
            >
              贴数信息
            </el-button>
          </div>
          <el-table
            v-if="producePieceList"
            :data="data.producePieceList"
            height="400"
            border
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            />
            <el-table-column
              v-if="route.query?.id && !copy"
              label="印刷序列号"
              width="120"
              prop="producePieceNo"
              align="center"
            ></el-table-column>
            <el-table-column
              label="品种"
              prop="breed"
              min-width="160"
              align="center"
            >
              <!-- <template #default="scope">
                                <dict-tag
                                    :options="ems_order_breed_type"
                                    :value="scope.row.breed"
                                />
                            </template> -->
            </el-table-column>
            <el-table-column
              label="印张"
              width="100"
              prop="sheet"
              align="center"
            ></el-table-column>
            <!-- <el-table-column
              label="lxjf"
              width="100"
              prop="lxjf"
              align="center"
            ></el-table-column> -->
            <el-table-column
              label="印数"
              width="100"
              prop="printAmount"
              align="center"
            ></el-table-column>
            <el-table-column
              label="贴标"
              width="120"
              prop="pieceView"
              align="center"
            ></el-table-column>
            <el-table-column
              label="工价类型"
              prop="wagesType"
              min-width="160"
              align="center"
            >
              <template #default="scope">
                <dict-tag
                  :options="production_wages_ype"
                  :value="scope.row.wagesType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="印刷方式"
              prop="printType"
              min-width="160"
              align="center"
            >
              <template #default="scope">
                <dict-tag
                  :options="mes_paper_package"
                  :value="scope.row.printType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="印刷状态"
              v-if="flag"
              width="120"
              prop="pressState"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.pressState == 1
                    ? "未完成"
                    : scope.row.pressState == 2
                    ? "已完成"
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="覆膜状态"
              v-if="flag"
              width="120"
              prop="coveringState"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.coveringState == 1
                    ? "未完成"
                    : scope.row.coveringState == 2
                    ? "已完成"
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="裁切状态"
              v-if="flag"
              width="120"
              prop="trimmingState"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.trimmingState == 1
                    ? "未完成"
                    : scope.row.trimmingState == 2
                    ? "已完成"
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="折页状态"
              v-if="flag"
              width="120"
              prop="foldState"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.foldState == 1
                    ? "未完成"
                    : scope.row.foldState == 2
                    ? "已完成"
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="装订状态"
              v-if="flag"
              width="120"
              prop="pressState"
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.bindingState == 1
                    ? "未完成"
                    : scope.row.bindingState == 2
                    ? "已完成"
                    : ""
                }}
              </template>
            </el-table-column>
          </el-table>
          <!-- <h4>备注</h4>
                    <el-input v-model="form.remark4" type="textarea" placeholder="请输入内容"></el-input> -->
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
    <productCovingList
      :visible="productCovingListOpen"
      @changeUpdate="productCovingData"
      :productCovingSelectList="productCovingSelectList"
      :params="params"
      @cancel="
        () => {
          productCovingListOpen = false;
        }
      "
    ></productCovingList>

    <!-- 1是内文 2是封面 -->
    <SearchPaperCoding
      :visible="paperOpen"
      :paperType="selectPaperType"
      :packageType="selectPackageType"
      :useType="'1'"
      @changeUpdate="changePaperData"
      @cancel="
        () => {
          paperOpen = false;
        }
      "
    ></SearchPaperCoding>
    <!-- :paperType="selectPaperType"
            :useType="'1'" -->
    <SearchPaperBD
      :visible="paperBDOpen"
      @changeUpdate="changePaperDataBD"
      @cancel="
        () => {
          paperBDOpen = false;
        }
      "
    ></SearchPaperBD>
    <SearchCustomer
      :visible="searchVisibleCustomer"
      @changeUpdate="changeSearchCustomer"
      @cancel="
        () => {
          searchVisibleCustomer = false;
        }
      "
    ></SearchCustomer>
    <ContactCover
      :visible="isShowFM"
      :orderId="orderId"
      @changeUpdate="handleContactFM"
      @cancel="
        () => {
          isShowFM = false;
          orderId = '';
        }
      "
    ></ContactCover>
    <JointPrint
      :visible="isJointShow"
      @changeUpdate="changeOrderJointData"
      @cancel="
        () => {
          isJointShow = false;
        }
      "
    ></JointPrint>
  </div>
</template>

<script setup>
import ContactCover from "./contactCover.vue";
import useUserStore from "@/store/modules/user";
import { toNumber } from "@/utils/ruoyi";
import { v4 as uuidv4 } from "uuid";
import orderList from "./orderList.vue";
import productCovingList from "./productCovingList.vue";
import { getPaperTonByParams } from "@/api/production/cover.js";
import { getCoefficient } from "@/api/basicInfo/PaperProduction.js";
import JointPrint from "./jointPrint.vue";
import { getputratio } from "@/api/basicInfo/workbench.js";
import SearchPaperCoding from "@/components/SearchPaperCoding";
import SearchCustomer from "@/components/SearchCustomer";
import useTagsViewStore from "@/store/modules/tagsView";
import SearchPaperBD from "./searchPaper.vue";
import { listPaper } from "@/api/basicInfo/paperCoding.js";
import { getTechnologyList } from "@/api/production/technics.js";
import { getList as getDataList } from "@/api/basicInfo/workbench";
import {
  addProduceOrderList,
  getProduceById,
  getWorkBench,
  getPubNo,
  getProduceCovingByOrderId,
  editProduce,
} from "@/api/production/cover";
import { getMesOrderInfo } from "@/api/production/order";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, onActivated } from "vue";
import { mestonnageList } from "@/api/basicInfo/coefficient";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  ems_produce_package_require,
  ems_machine_info_waste_rate,
  ems_produce_new_past,
  ems_order_binding_mode,
  ems_produce_finish_size,
  ems_produce_is_new,
  ems_produce_book_size,
  mes_paper_brand,
  mes_paper_package,
  ems_machine_info_size,
  mes_paper_material,
  mes_paper_specs,
  mes_paper_unit,
  ems_produce_color,
  mes_paper_type,
  ems_order_make_up,
  ems_order_breed_type,
  ems_order_print_color,
  ems_produce_paper_size,
  ems_order_pack_way,
  ems_workshop,
  production_wages_ype,
} = proxy.useDict(
  "ems_produce_package_require",
  "ems_machine_info_waste_rate",
  "ems_produce_new_past",
  "ems_produce_is_new",
  "ems_produce_finish_size",
  "mes_paper_package",
  "mes_paper_brand",
  "ems_produce_book_size",
  "ems_order_binding_mode",
  "mes_paper_unit",
  "mes_paper_specs",
  "mes_paper_material",
  "ems_machine_info_size",
  "ems_produce_color",
  "ems_produce_paper_size",
  "mes_paper_type",
  "ems_order_print_color",
  "ems_order_make_up",
  "ems_order_breed_type",
  "ems_order_pack_way",
  "ems_workshop",
  "production_wages_ype"
);
const route = useRoute();
const router = useRouter();
const activeNames = ["1", "2", "3", "4", "5", "6"];
const userRef = ref(null);
const orderListOpen = ref(false);
const productCovingListOpen = ref(false);
const producePrintListRef = ref(null);
const flag = ref(false);
const bookNoFlag = ref(true);
const selectedRow = ref([]);
const selectPaperType = ref(undefined);
const selectPaper = ref({});
const multiple = ref(true);
const copy = ref(false);
const selectPid = ref({});
const paperBDOpen = ref(false);
const paperIndex = ref(undefined);
const paperOpen = ref(false);
const selectPackageType = ref("");
const produceProductListForm = ref(null);
const producePaperListForm = ref(null);
const producePrintListForm = ref(null);
const bookCode = ref(undefined);
// const orderNoVal = ref(undefined)
const chnageState = ref([]);
const orderSelectList = ref([]);
//封面生产单
const productCovingSelectList = ref([]);
const listBPT = ref([]);
const technologyList = ref([]);
const searchVisibleCustomer = ref(false);
const searchVisible = ref(false);
const selectPrint = ref({});
const selectName = ref("");
const currentIndexJT = ref(0);
const stateIndex = ref(undefined);
const machineType = ref("");
const rowPaper = ref({});
const currentIndex = ref(0);
const params = ref({});
const coefficientList = ref([]);
const userInfo = useUserStore();
const isShowFM = ref(false);
const contactTextRow = ref({});
const orderId = ref("");
const isJointShow = ref(false);
const data = reactive({
  produceProductList: [], // 产品
  producePaperList: [], // 纸张
  producePrintList: [], // 印刷
  producePieceList: [],
  form: {
    type: "2",
    isNew: "1",
    customName: "出版社",
    customId: "5",
  },
  rules: {
    isNew: [{ required: true, message: "新/旧版不能为空", trigger: "blur" }],
    // fixPrice: [{ required: true, message: "定价不能为空", trigger: "blur" }],
    // submitDate: [{ required: true, message: "下单日期不能为空", trigger: "blur" },],
    pubNo: [{ required: true, message: "出版编号不能为空", trigger: "blur" }],
    orderCount: [
      { required: true, message: "订单数量不能为空", trigger: "blur" },
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" },
    ],
    workshopId: [{ required: true, message: "车间不能为空", trigger: "blur" }],
  },
});

const {
  form,
  rules,
  produceProductList,
  producePrintList,
  producePaperList,
  producePieceList,
} = toRefs(data);

// 关联封面
const showCover = (row) => {
  console.log(row);
  orderId.value = row.orderId;
  contactTextRow.value = row;
  isShowFM.value = true;
};
// 选中的关联生产单
const handleContactFM = (row) => {
  // console.log(produceProductList.value);
  nextTick(() => {
    produceProductList.value.forEach((item) => {
      if (item.orderProductId == contactTextRow.value.orderProductId) {
        item.produceIds =
          [
            ...new Set([
              ...(item.produceIds?.split(",") ?? []),
              ...row.map((obj) => obj.productId),
            ]),
          ].join(",") || "";
        item.produceNos =
          [
            ...new Set([
              ...(item.produceNos?.split(",") ?? []),
              ...row.map((obj) => obj.produceNo),
            ]),
          ].join(",") || "";
      }
    });
  });
  isShowFM.value = false;
};
const handleClose = (row, tag, index) => {
  produceProductList.value.forEach((item) => {
    if (item.orderProductId === row.orderProductId) {
      const produceIdsArray = item.produceIds ? item.produceIds.split(",") : [];
      const produceNosArray = item.produceNos ? item.produceNos.split(",") : [];
      produceIdsArray.splice(index, 1);
      produceNosArray.splice(index, 1);
      item.produceIds =
        produceIdsArray.length > 0 ? produceIdsArray.join(",") : null;
      item.produceNos =
        produceNosArray.length > 0 ? produceNosArray.join(",") : null;
    }
  });
};
const handleDeletePaper = (row, index) => {
  producePaperList.value.splice(index, 1);
};
// 平张获取损耗系数 版材 印色 印数
const getCoefficientP = async (sheetSize, printColour, printCount) => {
  let coefficient = 0;
  if (!sheetSize || !printColour || !printCount) {
    return coefficient;
  }
  // (Ps: 版材尺寸1055*811、1030*790 、930*721 损耗系数固定为0.03 )
  if (sheetSize == 5 || sheetSize == 6 || sheetSize == 2) {
    return (coefficient = 0.03);
  } else {
    if (printCount < 1000) {
      return (coefficient = 0);
    } else {
      try {
        const res = await getCoefficient({
          printType: 1,
          printColour,
          printCount,
        });
        if (res.code === 200) {
          coefficient = toNumber(Number(res.data) / 100, 4);
        }
      } catch (error) {}
    }
  }
  return coefficient;
};
// 卷筒获取损耗系数 版材 车间 印数
const getCoefficientJ = async (sheetSize, workshopId, printCount) => {
  let coefficient = 0;
  if (!sheetSize || !workshopId || !printCount) {
    return coefficient;
  }
  try {
    const res = await getCoefficient({
      printType: 2,
      sheetSize,
      workshopId,
      printCount,
    });

    if (res.code === 200) {
      coefficient = toNumber(Number(res.data) / 100, 4);
    }
  } catch (error) {}
  return coefficient;
};
// 调用
// getCoefficientP(sheetSize, printcolour, printcount)
//     .then(coefficient => {
//     })
// getCoefficientJ(sheetSize, workshopId, printcount)
//     .then(coefficient => {
//     })
//     .catch(error => {
//         // 处理错误
//     });
// 获取吨位系数
const getCoefficientList = () => {
  mestonnageList({ pageNum: 1, pageSize: 100 }).then((res) => {
    coefficientList.value = res.rows;
  });
};
getCoefficientList();
const changeLxjf = () => {
  mergeTotal(producePaperList.value, producePrintList.value);
};
onActivated(() => {
  if (route.query?.id) {
    getProduceById({ pid: route.query.id }).then((res) => {
      Object.assign(form.value, { ...res.data });
      // console.log(res.data.workshopName)
      if (res.data.irregularBooks) {
        const resp = JSON.parse(res.data.irregularBooks);
        listBPT.value = resp.listBPT;
        bookCode.value = resp.bookCode;
      }
      params.value = { orderId: res.data.orderId };
      produceProductList.value = res.data.produceProductList;
      producePrintList.value = res.data.producePrintList;
      producePaperList.value = res.data.producePaperList;
      producePieceList.value = res.data.producePieceList;
      producePieceList.value.forEach((item) => {
        producePrintList.value.forEach((obj) => {
          if (item.printId === obj.printId) {
            item.producePieceNo = obj.printProduceNo;
          }
        });
      });
      if (route.query.info) {
        flag.value = true;
      }
      // // 书号删除按钮需要增加权限控制，只给张秀娥和高秀芹
      // if((userInfo.name=="张秀娥" || userInfo.name=="高秀芹") && !flag){
      //   bookNoFlag.value=false;
      // }
      if (route.query.copy) {
        copy.value = true;
        form.value.mergePrintCode = null;
        // if (form.value.isNew == '1') {
        //     // form.value.pubNo = ''
        //     getPubNo().then(res => {
        //         form.value.pubNo = res.data
        //     })
        // } else {
        //     form.value.pubNo = ''
        // }
        //印刷次数
        if (form.value.orderId) {
          getMesOrderInfo({ pid: form.value.orderId }).then((res) => {
            if (res.rows.length > 0) {
              form.value.printNum = res.rows[0].printNum;
            }
          });
        }
        produceProductList.value.forEach((item) => {
          item.produceIds = null;
          item.produceNos = null;
          item.bindingStatus = 0;
          item.isGj = null;
        });
        producePrintList.value.forEach((item) => {
          item.whitecuttingMachine = undefined;
          item.printMachine = undefined;
          item.covercuttingMachine = undefined;
          item.coveringMachine = undefined;
          item.foldMachine = undefined;
          item.bindingMachine = undefined;
        });
        createdId(producePrintList.value);
        form.value.deliveryCount = undefined;
        form.value.urgentDate = undefined;
        form.value.urgentNum = undefined;
        form.value.isFp = null;
        producePieceList.value = [];
        listBPT.value.forEach((item) => {
          item.val = "";
        });
        bookCode.value = "";
      }
    });
  } else {
    // proxy.resetForm('userRef')
    // flag.value = false
    // copy.value = false
    // produceProductList.value = []
    // producePaperList.value = []
    // producePrintList.value = []
    // producePieceList.value = []
    // listBPT.value = []
    // bookCode.value = ''
    // 出版编号
    // getPubNo().then(res => {
    //     form.value.pubNo = res.data
    // })
  }
});
// 选择送货单位
const handleSelectCustomName = () => {
  searchVisibleCustomer.value = true;
};
const changeSearchCustomer = (row) => {
  form.value.customId = row.id;
  form.value.customName = row.name;
  searchVisibleCustomer.value = false;
};
const querySearch = (queryString, cb) => {
  const results = queryString
    ? ems_produce_package_require.value.filter(createFilter(queryString))
    : ems_produce_package_require.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
const handleSelect = (item) => {};
//20240326 added
const handlePrintWorkBranch = (row, index, type, name) => {
  if (!route.query.info) {
    //编辑
    //  type 机器类型
    selectName.value = name;
    machineType.value = type;
    selectPrint.value = row;
    searchVisible.value = true;
    //  state 2 印刷管理 state 3 贴数管理
    currentIndexJT.value = index;
    stateIndex.value = "2";
  } else {
    if (!name) {
      return;
    }
    const code = row[name].split("/")[3];
    //跳转详情
    getDataList({
      pageNum: 1,
      pageSize: 1,
      machineNo: code,
    }).then((res) => {
      if (res.code == 200) {
        // //跳转到机台
        router.push({
          path: "/basicInfo/workbench/details",
          query: {
            id: res.rows[0].pid,
            info: true,
            moduleCode: "textDetails",
            produceId: route.query.id,
          },
        });
      }
    });
  }
};
// 修改产品尺寸
const changeFinishSize = (row, index) => {
  producePrintList.value.forEach((item) => {
    if (row.orderProductId == item.orderProductId) {
      item.finishSize = row.finishSize;
    }
  });
};
// 半代435 可选择的纸
const clickFn = (row, index) => {
  if (flag.value) {
    return;
  }
  if (row.printType == 1) {
    return;
  }
  if (row.status != 1) {
    return;
  }
  rowPaper.value = row;
  currentIndex.value = index;
  paperBDOpen.value = true;
};

// 半代换纸
const changePaperDataBD = (row) => {
  let count = 0;
  producePrintList.value.forEach((obj) => {
    if (obj.paperNo == rowPaper.value.paperNo) {
      count++;
    }
  });
  if (count == 1) {
    producePaperList.value = producePaperList.value.filter(
      (item) => item.paperNo != rowPaper.value.paperNo
    );
  }

  const flag = producePaperList.value.some((ele) => ele.paperNo == row.paperNo);
  if (!flag) {
    row.paperInfoId = row.id;
    row.type = row.material?.toString();
    row.paperNo = row.code;
    row.printType = row.packageType?.toString(); // 印刷方式
    row.specifications = row.specs;
    row.paperSpecifications = row.specs;
    row.length = row.longWide;
    row.width = row.wide;
    row.unitPrice = row.authorityPrice;
    row.amount = row.quantity;
    row.paperName = row.name;
    // row.orderProductId = selectPid.value
    row.orderProductId =
      producePrintList.value[currentIndex.value].orderProductId;
    row.createTime = undefined;
    producePaperList.value.push({ ...row });
  }
  nextTick(() => {
    console.log(row);
    producePrintList.value[currentIndex.value].paperSpecifications = row.specs;
    producePrintList.value[currentIndex.value].paperNo = row.paperNo;
    producePrintList.value[currentIndex.value].weight = row.weight;
    producePrintList.value[currentIndex.value].clothWidth = row.longWide;
    producePrintList.value[currentIndex.value].brand = row.brand;
    producePrintList.value[currentIndex.value].paperName = row.name;
    // 汇总纸张的总令数
    mergeTotal(producePaperList.value, producePrintList.value);
  });

  producePaperList.value = producePaperList.value.reduce((acc, paper) => {
    const existingPaper = acc.find((item) => item.paperNo === paper.paperNo);
    if (!existingPaper) {
      acc.push({ ...paper });
    }
    return acc;
  }, []);

  paperBDOpen.value = false;
};
// 修改出版编号
const changePubNo = (row) => {
  produceProductList.value.forEach((item) => {
    item.pubNo = row;
  });
};
//  获取工艺
const getTechnologyArr = () => {
  getTechnologyList({ pageNum: 1, pageSize: 100 }).then((res) => {
    technologyList.value = res.rows;
  });
};
getTechnologyArr();
function onlyInteger(event) {
  const charCode = event.which ? event.which : event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    event.preventDefault();
  }
}
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  form.value.submitDate = `${year}-${month}-${day}`;
  // 将字符串转换为日期对象
  const submitDateObj = new Date(`${year}-${month}-${day}`);
  // 增加4天
  submitDateObj.setDate(submitDateObj.getDate() + 4);
  // 重新格式化为字符串
  form.value.deliverDate = `${submitDateObj.getFullYear()}-${String(
    submitDateObj.getMonth() + 1
  ).padStart(2, "0")}-${String(submitDateObj.getDate()).padStart(2, "0")}`;
  form.value.fileDate = `${year}-${month}-${day}`;
};
getCurrentDateTime();
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  if (route.query.moduleCode == "searchAccess") {
    router.push("/storage/searchAccess");
  } else if (route.query.moduleCode == "printReport") {
    router.go(-1);
  } else if (route.query.moduleCode == "makeVersion") {
    router.go(-1);
  } else if (route.query.moduleCode == "platemaking") {
    router.go(-1);
  } else if (route.query.moduleCode == "foldingReport") {
    router.push(
      "/Productionmanagementdistribution/Printingmanagement/foldingReport"
    );
  } else if (route.query.moduleCode == "waitTakeVersion") {
    router.push(
      "/Productionmanagementdistribution/Printingmanagement/waitTakeVersion"
    );
  } else if (route.query.moduleCode == "waitBindTask") {
    router.push(
      "/Productionmanagementdistribution/Bindingmanagement/waitBindTask"
    );
  } else if (route.query.moduleCode == "takeVersion") {
    router.push("/production/takeVersion");
  } else if (route.query.moduleCode == "Shippingdetails") {
    router.push("/Productionmanagementdistribution/production/Shippingdetails");
  } else if (route.query.moduleCode == "invoice") {
    router.push("/Productionmanagementdistribution/production/invoice");
  } else if (route.query.moduleCode == "searchReportDetail") {
    router.push(
      "/Productionmanagementdistribution/production/searchReportDetail"
    );
  } else if (route.query.moduleCode == "bindReport") {
    router.push(
      "/Productionmanagementdistribution/Bindingmanagement/bindReport"
    );
  } else if (route.query.moduleCode == "searchPlannedBindTasks") {
    router.push(
      "/Productionmanagementdistribution/Bindingmanagement/searchPlannedBindTasks"
    );
  } else if (route.query.moduleCode == "printScheduling") {
    router.push(
      "/Productionmanagementdistribution/Printingmanagement/printScheduling"
    );
  } else {
    router.push("/Productionmanagementdistribution/production/text");

    //router.replace({ path: '/production/text' })
    // setTimeout(() => {
    //     tagsViewStore.delView(route)
    // }, 0)
  }
};
const must = (obj) => {
  let mustColumns = [];
  mustColumns = [1, 5, 11, 12, 14, 16];
  // if (route.query?.id) {
  //     if (route.query.copy) {
  //         mustColumns = [1, 4, 7, 8, 10, 11,]
  //     } else {
  //         mustColumns = [2, 5, 9, 12, 13, 15, 16]
  //     }
  // } else {

  // }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const mustPaper = (obj) => {
  let mustColumns = [];
  if (route.query?.id) {
    if (route.query.copy) {
      mustColumns = [11];
    } else {
      mustColumns = [12];
    }
  } else {
    mustColumns = [11];
  }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
const mustPrint = (obj) => {
  let mustColumns = [];
  mustColumns = [17];
  // if (route.query?.id) {
  //     if (route.query.copy) {
  //         mustColumns = [14,15 ,16, ]
  //     } else {
  //         mustColumns = [17, 18, 19]
  //     }
  // } else {
  //     mustColumns = [16, 17, 18]
  // }
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// 主表订单数量修改
const changeOrderCount = (row) => {
  produceProductList.value.forEach((item) => {
    if (item.breed == "目录" && item.printColor == 4) {
      let count = 0;
      if (Number(row) <= 3999) {
        count = 30;
      } else if (Number(row) < 8000) {
        count = Math.floor(Number(row) / 1000) * 10;
      } else if (Number(row) < 10000) {
        count = 80;
      } else {
        count = Math.floor(Number(row) / 10000) * 80;
      }
      item.produceCount = Number(row) + count;
    } else {
      item.produceCount = row;
    }
    changeProduceCount(item);
  });
};
// // 内文贴数修改
// const changeTextPlateCount = (row, index) => {
//   // 印色*贴数
//   produceProductList.value[index].boardsCount =
//     printColorToLable(row.printColor) * Math.ceil(row.textPlateCount);
// };
//  新增产品信息
const handleAddProduceProductList = () => {
  orderSelectList.value = produceProductList.value;
  orderListOpen.value = true;
};
const handleJointPrint = () => {
  isJointShow.value = true;
};

const changeOrderJointData = (row) => {
  isJointShow.value = false;
  form.value.mergePrintCode = row.produceNo;
};
const handleAddProduceCovingList = () => {
  productCovingSelectList.value = productCovingSelectList.value;
  productCovingListOpen.value = true;
};

const findMakeUp = (val) => {
  const foundItem = ems_order_breed_type.value.find(
    (item) => item.value == val
  );
  if (foundItem) {
    return foundItem.label;
  }
};
// 全开
const handleQk = (row, index) => {
  proxy.$modal
    .confirm("是否确认全开？（温馨提示：如有半代，请先半代后再全开！）")
    .then(function () {
      row.isQk = "2";
      row.reamAmount = toNumber(
        (Number(row.printAmount) / 500) * Number(row.sheet),
        4
      );
      row.lossReam = toNumber(
        Number(row?.lossCoefficient || 0) * Number(row.reamAmount || 0),
        4
      );
      // 用纸总令数
      row.totalReamAmount = toNumber(
        Number(row?.lossCoefficient || 0) * Number(row.reamAmount || 0) +
          Number(row.reamAmount || 0),
        4
      );
      producePrintList.value.forEach((item) => {
        if (row.printId == item.printPid) {
          item.isQk = "2";
          item.reamAmount = toNumber(
            (Number(item.printAmount) / 500) * Number(item.sheet),
            4
          );
          item.lossReam = toNumber(
            Number(item?.lossCoefficient || 0) * Number(item.reamAmount || 0),
            4
          );
          // 用纸总令数
          item.totalReamAmount = toNumber(
            Number(item?.lossCoefficient || 0) * Number(item.reamAmount || 0) +
              Number(item.reamAmount || 0),
            4
          );
        }
      });
      mergeTotal(producePaperList.value, producePrintList.value);
    });
};
// 损耗系数发生改变
const changeLossCoefficient = (row, index) => {
  row.lossReam = toNumber(
    Number(row?.lossCoefficient || 0) * Number(row.reamAmount || 0),
    4
  );
  // 用纸总令数
  row.totalReamAmount = toNumber(
    Number(row?.lossCoefficient || 0) * Number(row.reamAmount || 0) +
      Number(row.reamAmount || 0),
    4
  );
  if (row.printType == 2) {
    if (row.tonnageCoefficient) {
      if (row.tonnageCoefficient) {
        row.rotateTon = toNumber(
          (Number(row.totalReamAmount) || 0) / Number(row.tonnageCoefficient),
          4
        );
      }
    }
  } else {
    row.rotateTon = undefined;
  }
  // 汇总纸张的总令数
  mergeTotal(producePaperList.value, producePrintList.value);
};
// 损耗系数发生改变
const changeLossCoefficientTTT = (row, index) => {
  producePrintList.value[index].lossReam = toNumber(
    Number(producePrintList.value[index]?.lossCoefficient || 0) *
      Number(row.reamAmount || 0),
    4
  );
  // 用纸总令数
  producePrintList.value[index].totalReamAmount = toNumber(
    Number(producePrintList.value[index]?.lossCoefficient || 0) *
      Number(row.reamAmount || 0) +
      Number(row.reamAmount || 0),
    4
  );
  if (row.printType == 2) {
    if (producePrintList.value[index].tonnageCoefficient) {
      producePrintList.value[index].rotateTon = toNumber(
        Number(producePrintList.value[index].totalReamAmount || 0) /
          Number(producePrintList.value[index].tonnageCoefficient),
        4
      );
    }
  } else {
    producePrintList.value[index].rotateTon = undefined;
  }
  // 汇总纸张的总令数
  mergeTotal(producePaperList.value, producePrintList.value);
};
// 印张发生改变
const changeSheet = (row, index) => {
  produceProductList.value[index].boardsCount =
    (produceProductList.value[index].printColor
      ? printColorToLable(produceProductList.value[index].printColor)
      : 0) * (Math.ceil(Number(produceProductList.value[index].sheet)) || 0);
  produceProductList.value[index].sheetAmount =
    produceProductList.value[index].boardsCount;
  producePrintList.value.forEach((item, index) => {
    if (item.status) {
      producePrintList.value.splice(index, 1);
    }
    if (item.orderProductId === row.orderProductId && !item.status) {
      item.sheet = row.sheet;
      item.reamAmount = toNumber(
        ((Number(item.printAmount) || 0) / 1000) * Number(item.sheet),
        4
      );
      item.lossReam = toNumber(
        (item.lossCoefficient || 0) * Number(item.reamAmount),
        4
      );
      item.totalReamAmount = toNumber(item.reamAmount + item.lossReam, 4);
    }
  });
  mergeTotal(producePaperList.value, producePrintList.value);
};
//  生产数量改变 印数重新计算
const changeProduceCount = (row) => {
  producePrintList.value.forEach((item, index) => {
    if (item.orderProductId === row.orderProductId) {
      item.printAmount = row.produceCount || 0;
      item.reamAmount = toNumber(
        (Number(row.produceCount) / 1000) * Number(item.sheet),
        4
      );
      //20240326 提交的时候自动分配机台
      // if (item.sheetSize) {
      //     changeWorkBranch(item, index)
      // }
      if (item.printType == 1) {
        if (item.printAmount < 1000) {
          // 另行加放
          // 平张：印数<1000的时候，另行加放为印张*80/1000
          item.lxjf = toNumber((item.sheet * 80) / 1000, 4);
        } else {
          item.lxjf = undefined;
        }
        getCoefficientP(
          item.sheetSize,
          item.printColour,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      } else {
        getCoefficientJ(
          item.sheetSize,
          form.value.workshopId,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      }
    }
    // item.sheetAmount = printColorToLable(item.printColor) * Number(item.sheet)
  });
  handleProducePiece();
};
//  贴标修改
const changeLabeling = () => {
  // 贴数重新生成
  handleProducePiece();
};
// 吨位系数发生改变
const handleTonnageCoefficient = (row, index) => {
  if (producePrintList.value[index].tonnageCoefficient) {
    producePrintList.value[index].rotateTon = toNumber(
      Number(producePrintList.value[index].totalReamAmount || 0) /
        Number(producePrintList.value[index].tonnageCoefficient),
      4
    );
    mergeTotal(producePaperList.value, producePrintList.value);
  } else {
    producePrintList.value[index].rotateTon = 0;
  }
};

//获取封面生产单编码
const productCovingData = (row) => {
  form.value.produceCoveringNo = row.produceNo;
  productCovingListOpen.value = false;
};

// 获取产品信息
const changeOrderData = (row) => {
  console.log(row);
  form.value.packInNum = row[0].packInNum;
  form.value.printNo = row[0].printNo;
  form.value.packageRequire = row[0].packageRequire;
  form.value.packWay = row[0].packWay;
  form.value.fileDate = row[0].fileDate;

  form.value.pubNo = row[0].pubNo;
  form.value.fixPrice = row[0].fixPrice;
  // productName
  params.value = { orderId: row[0].orderId };
  form.value.orderId = row[0].orderId;
  form.value.productName =
    (row[0].bookCode || "") + " " + (row[0].bookName || "");
  form.value.shipmentType = form.value.productName;
  form.value.publishingHouse = row[0].publishingHouse;
  form.value.bookNo = row[0].bookNo;
  form.value.printNum = row[0].printNum;
  listBPT.value = row.map((item) => {
    const existingItem = listBPT.value.find(
      (listItem) => listItem.id == item.orderProductId
    );
    if (existingItem) {
      return {
        ...existingItem,
        val: existingItem.val,
      };
    }
    return {
      id: item.orderProductId,
      name: item.bookCode + "/" + item.breedType,
      val: "",
    };
  });

  produceProductList.value = row.map((item) => {
    item.produceCount = form.value.orderCount || 0;
    if (item.breed == "目录" && item.printColor == 4) {
      let count = 0;
      if (Number(form.value.orderCount) <= 3999) {
        count = 30;
      } else if (Number(form.value.orderCount) < 8000) {
        count = Math.floor(Number(form.value.orderCount) / 1000) * 10;
      } else if (Number(form.value.orderCount) < 10000) {
        count = 80;
      } else {
        count = Math.floor(Number(form.value.orderCount) / 10000) * 80;
      }
      item.produceCount = Number(form.value.orderCount || 0) + count;
    } else {
      item.produceCount = form.value.orderCount || 0;
    }
    // (item.boardsCount =
    //   printColorToLable(item.printColor) * Math.ceil(item.textPlateCount));
    const existingItem = produceProductList.value.find(
      (listItem) => listItem.orderProductId == item.orderProductId
    );
    // 如果存在相同 id 的项，则保留其 value 值
    if (existingItem) {
      return {
        ...existingItem,
        // boardsCount : * item.sheet
        // newPast: existingItem.newPast,
        // produceCount: existingItem.produceCount,
        // bookSize: existingItem.bookSize,
        // color: existingItem.color,
        // paperSize: existingItem.paperSize,
        // paperType: existingItem.paperType,
        // paperNo: existingItem.paperNo,
        // paperName: existingItem.paperName,
        // kaoban: existingItem.kaoban,
        // sheetSize: existingItem.sheetSize,
        // textPlateCount: existingItem.textPlateCount,
        // boardsCount: existingItem.boardsCount,
        // sheetAmount: existingItem.boardsCount,
        // sheet: existingItem.sheet,
        // pubNo: existingItem.pubNo,
      };
    } else {
      return {
        ...item,
        // pubNo: item.pubNo ? item.pubNo : form.value.pubNo,
        pubNo: item.pubNo,
        paperType: "2",
      };
    }
  });
  producePrintList.value = row.map((item) => {
    const existingItem = producePrintList.value.find(
      (listItem) => listItem.orderProductId == item.orderProductId
    );
    // 如果存在相同 id 的项，则保留其 value 值
    if (existingItem) {
      return {
        ...existingItem,
      };
    } else {
      // item.printId = uuidv4();

      return {
        sheetAmount: item.boardsCount,
        printId: uuidv4(),
        // sheetAmount: printColorToLable(item.printColor) * Number(item.sheet), //  印色 *  印张 （封面默认1）= 版材数量
        // orderPrintCount: item.orderPrintCount,
        printColour: item.printColor, // 印色
        finishSize: item.finishSize, //成品尺寸
        sheetSize: item.sheetSize,
        bookNo: item.bookCode,
        bookName: item.bookName,
        breed: item.breedType,
        sheet: item.printSheet,
        orderProductId: item.orderProductId,
        composition: item.makeUp,
        printAmount: item.produceCount || 0,
        reamAmount: toNumber(
          (Number(item.produceCount || 0) / 1000) * Number(item.sheet),
          4
        ),
        printColour: item.printColor,
        printCount: item.printSheet,
        tonnageCoefficient: 0,
        lossCoefficient: 0,
      };
    }
  });
  // producePrintList.value.forEach((item) => {
  //   if (item.printType == 2) {
  //     if (Number(item.sheet) % 1 === 0.5 && Number(item.sheet) !== 0.5) {
  //       handleHalfAutomatic(item);
  //     }
  //   }
  // });

  handleProducePiece();
  orderListOpen.value = false;
};
// 自动半代
// const modifiedList = [];
// originalList.forEach((item) => {
//   if (item.sheet % 1 === 0.5) {
//     modifiedList.push({
//       sheet: 0.5,
//       id: item.id,
//     });
//     modifiedList.push({
//       sheet: item.sheet - 0.5,
//       id: item.id,
//     });
//   } else {
//     modifiedList.push(item);
//   }
// });
const printColorToLable = (row) => {
  const resp = ems_order_print_color.value.filter((item) => item.value == row);
  return eval(resp[0].label);
};
// 被选中
const handleSelectionChange = (row) => {
  chnageState.value = row;
};
// 选择纸张编码
const openPaperDialog = (row, index) => {
  if (row.sheetSize == "3" || row.sheetSize == "9") {
    // 卷筒版材尺寸 过滤纸
    selectPackageType.value = 2;
  } else {
    selectPackageType.value = 1;
  }
  selectPaperType.value = row.paperType;
  selectPid.value = row.orderProductId;
  paperIndex.value = index;
  paperOpen.value = true;
};
// 印刷 选中的数据
const handlePrintChange = (selection) => {
  multiple.value = !selection.length;
  selectedRow.value = selection;
  if (selection.length > 1) {
    // 只保留最后选中的一行
    let lastSelectedRow = selection.pop();
    producePrintListRef.value.toggleRowSelection(lastSelectedRow);
  }
};
// 自动半代
const handleHalfAutomatic = (row) => {
  //  印张sheet
  // if (selectedRow.value[0].sheet == 0.5) {
  //   return ElMessage({
  //     message: "印张不足0.5,无法分配",
  //     type: "warning",
  //   });
  // } else {
  const list = [];
  list.push(row);
  splitHalfDate(list);
  producePrintListRef.value.clearSelection();
  nextTick(() => {
    mergeTotal(producePaperList.value, producePrintList.value);
    handleProducePiece();
  });
};
const paperSpecialList = ref([]);
// 半代 指定435 纸张
const getPaper = () => {
  listPaper({ longWide: 435 }).then((res) => {
    // 全部的435 纸张
    paperSpecialList.value = res.rows;
    selectPaper.value = { ...res.rows[0] };
  });
};
getPaper();
// 半代
const handleHalf = () => {
  if (selectedRow.value) {
    //  印张sheet
    if (selectedRow.value[0].sheet == 0.5) {
      return ElMessage({
        message: "印张不足0.5,无法分配",
        type: "warning",
      });
    } else if (selectedRow.value[0].status == 2) {
      return ElMessage({
        message: "整代无法进行分配",
        type: "warning",
      });
    } else {
      splitHalfDate(selectedRow.value, 0.5);
      producePrintListRef.value.clearSelection();
      nextTick(() => {
        mergeTotal(producePaperList.value, producePrintList.value);
        handleProducePiece();
      });
    }
  }
};
// 自定义半代
const handleDIY = () => {
  ElMessageBox.prompt("请输入半代值", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^(0\.\d*[1-9])|(0+\.\d*)$/,
    inputErrorMessage: "请输入0-1之间",
  })
    .then(({ value }) => {
      // ElMessage({
      //   type: "success",
      //   message: `Your email is:${value}`,
      // });
      if (selectedRow.value) {
        //  印张sheet
        splitHalfDateDIY(selectedRow.value, value);
        producePrintListRef.value.clearSelection();
        nextTick(() => {
          mergeTotal(producePaperList.value, producePrintList.value);
          handleProducePiece();
        });
      }
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Input canceled",
      // });
    });
};
const handleHalfAuto = () => {
  if (producePrintList.value.length == 0) {
    return;
  }
  const list = producePrintList.value.filter((item) =>
    hasRemainderHalf(item.sheet)
  );
  list.forEach((obj) => {
    selectedRow.value = [obj];
    handleHalf();
  });
  // producePrintList.value.forEach(item => {
  //     if (hasRemainderHalf(item.sheet)) {
  //         selectedRow.value = [item]
  //         handleHalf()
  //     }
  // })
};
function hasRemainderHalf(num) {
  return num - Math.floor(num) === 0.5 && num > 0.5;
}

// 半代数据分割
const splitHalfDateDIY = (arr, bdValue) => {
  // 分割数据并替换
  arr.forEach((item, index) => {
    const matchingIndex = producePrintList.value.findIndex(
      (listItem) => listItem.printId === item.printId
    );
    if (matchingIndex !== -1) {
      if (!item.printType) {
        return ElMessage({
          message: "请先选择纸张",
          type: "warning",
        });
      }
      const matchingItem = producePrintList.value[matchingIndex];
      item.reamAmount = toNumber(
        (Number(item.printAmount || 0) / 1000) * Number(item.sheet - bdValue),
        4
      );
      item.lossReam = toNumber(
        (item.lossCoefficient || 0) * Number(item.reamAmount || 0),
        4
      );
      // 用纸总令数计算

      // 平张贴标从2开始 卷筒从1 （只有半代）
      // 先判断 装订方式 是不是倒装再判断开本数 印张
      const resp = produceProductList.value.filter(
        (item) =>
          item.orderProductId ==
          producePrintList.value[matchingIndex].orderProductId
      );
      producePrintList.value[matchingIndex].counter = producePrintList.value[
        matchingIndex
      ].counter
        ? producePrintList.value[matchingIndex].counter + 1
        : producePrintList.value[matchingIndex].printType == 1
        ? 2
        : producePrintList.value[matchingIndex].printType == 2
        ? 1
        : undefined;
      producePrintList.value.splice(
        matchingIndex,
        1,
        {
          ...item,
          totalReamAmount: toNumber(
            (item.lossCoefficient || 0) * Number(item.reamAmount || 0) +
              Number(item.reamAmount || 0),
            4
          ),
          sheet: parseFloat(item.sheet) - bdValue,
          // 纸张克重
          zjkg: item.paperWeight,
          rotateTon:
            item.printType == 2
              ? toNumber(
                  item.tonnageCoefficient
                    ? ((item.lossCoefficient || 0) * Number(item.reamAmount) +
                        Number(item.reamAmount || 0)) /
                        Number(item.tonnageCoefficient || 1)
                    : 0,
                  4
                )
              : undefined,
        },
        {
          ...item,
          ...matchingItem,
          technologyId:
            matchingItem.printType == 1
              ? "1796079690537132033"
              : "5e00358c965c4b40bb286d2c1f4a2e54",
          printId: uuidv4(),
          printPid: item.printId,
          status: 1,
          //  轮转吨数=用纸总令数*吨位系数
          reamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * Number(bdValue),
            4
          ),
          lossReam: toNumber(
            (matchingItem.lossCoefficient || 0) *
              ((Number(matchingItem.printAmount) / 1000) * Number(bdValue)),
            4
          ),
          totalReamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * Number(bdValue) +
              (((matchingItem.lossCoefficient || 0) *
                Number(matchingItem.printAmount)) /
                1000) *
                Number(bdValue),
            4
          ),
          rotateTon:
            matchingItem.printType == 2
              ? toNumber(
                  matchingItem.tonnageCoefficient
                    ? ((Number(matchingItem.printAmount) / 1000) *
                        Number(bdValue) +
                        (((matchingItem.lossCoefficient || 0) *
                          Number(matchingItem.printAmount)) /
                          1000) *
                          Number(bdValue) || 0) /
                        Number(matchingItem.tonnageCoefficient || 1)
                    : 0,
                  4
                )
              : undefined,
          // 轮转吨数
          sheet: Number(bdValue),
          labeling:
            resp[0]?.bindingMode == 3
              ? ""
              : resp[0]?.bookSize == 1
              ? Math.ceil(producePrintList.value[matchingIndex].sheet) - 1
              : producePrintList.value[matchingIndex].counter,
        }
      );
    }
  });
  nextTick(() => {
    mergeTotal(producePaperList.value, producePrintList.value);
    handleProducePiece();
  });
};

// 半代数据分割
const splitHalfDate = (arr, bdValue) => {
  // 分割数据并替换
  arr.forEach((item, index) => {
    const matchingIndex = producePrintList.value.findIndex(
      (listItem) => listItem.printId === item.printId
    );
    if (matchingIndex !== -1) {
      if (!item.printType) {
        return ElMessage({
          message: "请先选择纸张",
          type: "warning",
        });
      }
      const matchingItem = producePrintList.value[matchingIndex];
      item.reamAmount = toNumber(
        (Number(item.printAmount || 0) / 1000) * Number(item.sheet - 0.5),
        4
      );
      item.lossReam = toNumber(
        (item.lossCoefficient || 0) * Number(item.reamAmount || 0),
        4
      );
      // 用纸总令数计算

      // 平张贴标从2开始 卷筒从1 （只有半代）
      // 先判断 装订方式 是不是倒装再判断开本数 印张
      const resp = produceProductList.value.filter(
        (item) =>
          item.orderProductId ==
          producePrintList.value[matchingIndex].orderProductId
      );
      producePrintList.value[matchingIndex].counter = producePrintList.value[
        matchingIndex
      ].counter
        ? producePrintList.value[matchingIndex].counter + 1
        : producePrintList.value[matchingIndex].printType == 1
        ? 2
        : producePrintList.value[matchingIndex].printType == 2
        ? 1
        : undefined;
      // if (item.printType == 2)  如果是轮转 指定纸张
      if (item.printType == 2) {
        // 查看纸张编码中有这个纸吗 没有的话加上
        // if (!producePaperList.value.some((item) => item.paperNo === 'ZZGL202403010003')) {
        const hasSameBrand = {
          ...paperSpecialList.value.filter(
            (ele) => ele.brand === item.brand
          )[0],
        };
        // let hasSameBrand = {}
        // paperSpecialList.value.forEach(
        //   ele => {
        //     if (ele.brand === item.brand) {
        //       hasSameBrand = {...ele}
        //     }
        //   }
        // )
        if (Object.keys(hasSameBrand).length !== 0) {
          // 存在相同的品牌
          console.log("存在相同的品牌", hasSameBrand, item);
          selectPaper.value.paperInfoId = hasSameBrand.id;
          selectPaper.value.type = hasSameBrand.material?.toString();
          selectPaper.value.paperNo = hasSameBrand.code;
          selectPaper.value.paperName = hasSameBrand.name;
          selectPaper.value.printType = hasSameBrand.packageType?.toString(); // 印刷方式
          selectPaper.value.specifications = hasSameBrand.specs;
          selectPaper.value.paperSpecifications = hasSameBrand.specs;
          selectPaper.value.length = hasSameBrand.longWide;
          selectPaper.value.width = hasSameBrand.wide;
          selectPaper.value.brand = hasSameBrand.brand;
          // 定量
          selectPaper.value.weight = hasSameBrand.weight;
          selectPaper.value.unitPrice = hasSameBrand.authorityPrice;
          selectPaper.value.amount = hasSameBrand.quantity;
          selectPaper.value.orderProductId = item.orderProductId;
          selectPaper.value.createTime = undefined;
        } else {
          // 不存在相同的品牌
          console.log("不存在相同的品牌", selectPaper, item);
          selectPaper.value.paperInfoId = paperSpecialList.value[0].id;
          selectPaper.value.type =
            paperSpecialList.value[0].material?.toString();
          selectPaper.value.paperNo = paperSpecialList.value[0].code;
          selectPaper.value.paperName = paperSpecialList.value[0].name;
          selectPaper.value.printType = paperSpecialList.value[0]?.toString(); // 印刷方式
          selectPaper.value.specifications = paperSpecialList.value[0].specs;
          selectPaper.value.paperSpecifications =
            paperSpecialList.value[0].specs;
          selectPaper.value.length = paperSpecialList.value[0].longWide;
          selectPaper.value.width = paperSpecialList.value[0].wide;
          selectPaper.value.brand = paperSpecialList.value[0].brand;
          selectPaper.value.unitPrice =
            paperSpecialList.value[0].authorityPrice;
          selectPaper.value.amount = paperSpecialList.value[0].quantity;
          selectPaper.value.orderProductId = item.orderProductId;
          selectPaper.value.weight = paperSpecialList.value[0].weight;
          selectPaper.value.createTime = undefined;
        }
        const flag = producePaperList.value.some(
          (item) => item.paperNo == selectPaper.value.paperNo
        );
        if (!flag) {
          producePaperList.value.push({ ...selectPaper.value });
        }
        // }
      }
      producePrintList.value.splice(
        matchingIndex,
        1,
        {
          ...item,
          totalReamAmount: toNumber(
            (item.lossCoefficient || 0) * Number(item.reamAmount || 0) +
              Number(item.reamAmount || 0),
            4
          ),
          sheet: parseFloat(item.sheet) - 0.5,

          // 印数
          lxjf:
            item.printType == 2
              ? 0.0124
              : item.printAmount < 1000
              ? toNumber(((item.sheet - 0.5) * 80) / 1000, 4)
              : undefined,
          // 纸张克重
          zjkg: item.paperWeight,
          rotateTon:
            item.printType == 2
              ? toNumber(
                  item.tonnageCoefficient
                    ? ((item.lossCoefficient || 0) * Number(item.reamAmount) +
                        Number(item.reamAmount || 0)) /
                        Number(item.tonnageCoefficient || 1)
                    : 0,
                  4
                )
              : undefined,
        },
        {
          ...item,
          ...matchingItem,
          technologyId:
            matchingItem.printType == 1
              ? "1796079690537132033"
              : "5e00358c965c4b40bb286d2c1f4a2e54",
          paperNo:
            matchingItem.printType == 2
              ? selectPaper.value.paperNo
              : matchingItem.paperNo,
          paperName:
            matchingItem.printType == 2
              ? selectPaper.value.name
              : matchingItem.paperName,
          paperType:
            matchingItem.printType == 2
              ? selectPaper.value.paperType
              : matchingItem.paperType,
          weight:
            matchingItem.printType == 2
              ? selectPaper.value.weight
              : matchingItem.weight,
          paperSpecifications:
            matchingItem.printType == 2
              ? selectPaper.value.specs
              : matchingItem.paperSpecifications,
          clothWidth:
            matchingItem.printType == 2
              ? selectPaper.value.longWide
              : matchingItem.clothWidth,
          brand:
            matchingItem.printType == 2
              ? selectPaper.value.brand
              : matchingItem.brand,
          // lossReam: item.lossReam,
          printId: uuidv4(),
          printPid: item.printId,
          lxjf:
            item.printType == 2
              ? 0.0062
              : matchingItem.printAmount < 1000
              ? toNumber((0.5 * 80) / 1000, 4)
              : undefined,
          status: 1,
          //  轮转吨数=用纸总令数*吨位系数

          reamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * 0.5,
            4
          ),
          lossReam: toNumber(
            (matchingItem.lossCoefficient || 0) *
              ((Number(matchingItem.printAmount) / 1000) * 0.5),
            4
          ),
          totalReamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * 0.5 +
              (((matchingItem.lossCoefficient || 0) *
                Number(matchingItem.printAmount)) /
                1000) *
                0.5,
            4
          ),
          rotateTon:
            matchingItem.printType == 2
              ? toNumber(
                  matchingItem.tonnageCoefficient
                    ? ((Number(matchingItem.printAmount) / 1000) * 0.5 +
                        (((matchingItem.lossCoefficient || 0) *
                          Number(matchingItem.printAmount)) /
                          1000) *
                          0.5 || 0) /
                        Number(matchingItem.tonnageCoefficient || 1)
                    : 0,
                  4
                )
              : undefined,
          // 轮转吨数
          sheet: 0.5,
          labeling:
            resp[0]?.bindingMode == 3
              ? ""
              : resp[0]?.bookSize == 1
              ? Math.ceil(producePrintList.value[matchingIndex].sheet) - 1
              : producePrintList.value[matchingIndex].counter,
        }
      );
    }
  });
  nextTick(() => {
    mergeTotal(producePaperList.value, producePrintList.value);
    handleProducePiece();
  });
};
// const splitHalfDate = (arr) => {
//     // 分割数据并替换
//     arr.forEach((item, index) => {
//         const matchingIndex = producePrintList.value.findIndex((listItem) => listItem.printId === item.printId);
//         if (matchingIndex !== -1) {
//             const matchingItem = producePrintList.value[matchingIndex];
//             matchingItem.reamAmount = toNumber((Number(matchingItem.printAmount) / 1000 * Number(matchingItem.sheet - 0.5)), 4)
//             matchingItem.lossReam = toNumber((matchingItem.lossCoefficient || 0 * Number(matchingItem.reamAmount) / 100), 4)
//             matchingItem.totalReamAmount = toNumber((matchingItem.lossCoefficient || 0 * Number(matchingItem.reamAmount) / 100) + Number(matchingItem.reamAmount), 4)
//             console.log(matchingItem.totalReamAmount,'21');
//             producePrintList.value.splice(matchingIndex, 1, { ...matchingItem, sheet: parseFloat(matchingItem.sheet) - 0.5, }, { ...item, printId: uuidv4(), status: 1, reamAmount: toNumber((Number(matchingItem.printAmount) / 1000 * 0.5), 4), sheet: 0.5, });
//         }
//     });
//     nextTick(() => {
//         mergeTotal(producePaperList.value, producePrintList.value)
//     })
// }

// 整代
const handleWhole = () => {
  if (selectedRow.value) {
    //  印张sheet
    if (selectedRow.value[0].sheet <= 1) {
      return ElMessage({
        message: "印张不足,无法分配",
        type: "warning",
      });
    } else {
      splitWholeDate(selectedRow.value);
      producePrintListRef.value.clearSelection();
      nextTick(() => {
        mergeTotal(producePaperList.value, producePrintList.value);
      });
    }
  }
};
// 整代数据分割
const splitWholeDate = (arr) => {
  // 分割数据并替换
  arr.forEach((item, index) => {
    const matchingIndex = producePrintList.value.findIndex(
      (listItem) => listItem.printId === item.printId
    );
    if (matchingIndex !== -1) {
      const matchingItem = producePrintList.value[matchingIndex];
      item.reamAmount = toNumber(
        (Number(item.printAmount) / 1000) * Number(item.sheet - 1),
        4
      );
      item.lossReam = toNumber(
        item.lossCoefficient || 0 * Number(item.reamAmount),
        4
      );
      matchingItem.totalReamAmount =
        toNumber((Number(matchingItem.printAmount) / 1000) * 1, 4) +
        item.lossReam;
      producePrintList.value.splice(
        matchingIndex,
        1,
        {
          ...item,
          totalReamAmount: toNumber(
            (item.lossCoefficient || 0) * Number(item.reamAmount) +
              Number(item.reamAmount),
            4
          ),

          sheet: parseFloat(item.sheet) - 1,
          rotateTon: toNumber(
            item.tonnageCoefficient
              ? ((item.lossCoefficient || 0) * Number(item.reamAmount) +
                  Number(item.reamAmount || 0)) /
                  Number(item.tonnageCoefficient || 1)
              : 0,
            4
          ),
        },
        {
          ...item,
          ...matchingItem,
          lossReam: item.lossReam,
          printId: uuidv4(),
          printPid: item.printId,
          status: 2,
          reamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * 1,
            4
          ),
          technologyId:
            matchingItem.printType == 1
              ? "1814131428749955074"
              : "1814123849399357442",
          lossReam: toNumber(
            (matchingItem.lossCoefficient || 0) *
              ((Number(matchingItem.printAmount) / 1000) * 1),
            4
          ),
          totalReamAmount: toNumber(
            (Number(matchingItem.printAmount) / 1000) * 1 +
              (((matchingItem.lossCoefficient || 0) *
                Number(matchingItem.printAmount)) /
                1000) *
                1,
            4
          ),
          rotateTon: toNumber(
            matchingItem.tonnageCoefficient
              ? ((Number(matchingItem.printAmount) / 1000) * 1 +
                  (((matchingItem.lossCoefficient || 0) *
                    Number(matchingItem.printAmount)) /
                    1000) *
                    1 || 0) / Number(matchingItem.tonnageCoefficient || 1)
              : 0,
            4
          ),
          sheet: 1,
        }
      );
    }
  });
};
// // 整代数据分割
// const splitWholeDate = (arr) => {
//     // 分割数据并替换
//     arr.forEach((item, index) => {
//         const matchingIndex = producePrintList.value.findIndex((listItem) => listItem.printId === item.printId);
//         if (matchingIndex !== -1) {
//             const matchingItem = producePrintList.value[matchingIndex];
//             matchingItem.reamAmount = toNumber((Number(matchingItem.printAmount) / 1000 * Number(matchingItem.sheet - 1)), 4)
//             matchingItem.lossReam = toNumber((matchingItem.lossCoefficient || 0 * Number(matchingItem.reamAmount) / 100), 4)
//             matchingItem.totalReamAmount = toNumber((matchingItem.lossCoefficient || 0 * Number(matchingItem.reamAmount) / 100) + Number(matchingItem.reamAmount), 4)
//             producePrintList.value.splice(matchingIndex, 1, { ...matchingItem, sheet: parseFloat(matchingItem.sheet) - 1 }, { ...item, reamAmount: toNumber((Number(matchingItem.printAmount) / 1000), 4), status: 2, printId: uuidv4(), sheet: 1, });
//         }
//     });
// }
// 贴数删除
const handleDeleteTs = (row) => {
  producePrintList.value.forEach((item) => {
    if (item.printId == row.printPid) {
      item.isQk = "1";
    }
  });
  let info = "";
  if (row.isQk == "2") {
    info = "是否确认删除该贴数信息？(温馨提示： 删除后需要重新全开)";
  } else {
    info = "是否确认删除该贴数信息？";
  }
  proxy.$modal.confirm(info).then(function () {
    // if (row.status == 1) {
    //   delAccumulate(row, 0.5);
    // } else if (row.status == 2) {
    //   delAccumulate(row, 1);
    // }
    delAccumulate(row, Number(row.sheet));
    const filteredList = producePrintList.value.filter(
      (item) => item.paperNo == row.paperNo
    );
    if (filteredList.length === 1) {
      producePaperList.value = producePaperList.value.filter(
        (ele) => ele.paperNo != row.paperNo
      );
    }
    producePrintList.value = producePrintList.value.filter(
      (val) => val.printId != row.printId
    );
    // 重新生成贴数
    if (producePieceList.value.length > 0) {
      handleProducePiece();
    }
    mergeTotal(producePaperList.value, producePrintList.value);
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 平张卷筒切换 贴数回滚
const handleDeleteTsBack = (row) => {
  // const ele = producePrintList.value.find(
  //   (val) => val.printPid === row.printId
  // );
  producePrintList.value.forEach((ele) => {
    if (ele.printPid == row.printId) {
      // if (ele.status == 1) {
      //   delAccumulate(ele, 0.5);
      // } else if (ele.status == 2) {
      //   delAccumulate(ele, 1);
      // }
      delAccumulate(ele, Number(ele.sheet));
      producePrintList.value = producePrintList.value.filter(
        (val) => val.printId != ele.printId
      );
    }
  });
  const filteredList = producePrintList.value.filter(
    (item) => item.paperNo == row.paperNo
  );
  if (filteredList.length === 1) {
    producePaperList.value = producePaperList.value.filter(
      (ele) => ele.paperNo != row.paperNo
    );
  }
  // 重新生成贴数
  if (producePieceList.value.length > 0) {
    handleProducePiece();
  }
  mergeTotal(producePaperList.value, producePrintList.value);
};

// 贴数删除累加
const delAccumulate = (row, count) => {
  producePrintList.value.forEach((item) => {
    if (item.printId === row.printPid) {
      if (count == 0.5) {
        item.counter = Number(item.counter) - 1; //贴标+1
      }
      item.sheet = Number(item.sheet) + Number(count);
      item.reamAmount = toNumber(
        (Number(item.printAmount || 0) / 1000) * Number(item.sheet),
        4
      );
      item.totalReamAmount = toNumber(
        Number(item.lossCoefficient || 0) * Number(item.reamAmount || 0) +
          Number(item.reamAmount || 0),
        4
      );
      changeLossCoefficient(item);
    }
  });
};
const tableRowClassName = ({ row, rowIndex }) => {
  if (chnageState.value.some((item) => item.pid === row.breedPid)) {
    return "success-row";
  } else {
    return "";
  }
};
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该产品信息及相关信息？").then(function () {
    // 改变不配套图书
    listBPT.value = listBPT.value.filter(
      (item) => item.id != row.orderProductId
    );
    const isUnique =
      produceProductList.value.filter((item) => item.paperNo === row.paperNo)
        .length == 1;
    if (isUnique) {
      producePaperList.value = producePaperList.value.filter(
        (item) => item.orderProductId !== row.orderProductId
      );
    }
    produceProductList.value = produceProductList.value.filter(
      (item) => item.orderProductId !== row.orderProductId
    );
    producePrintList.value = producePrintList.value.filter(
      (item) => item.orderProductId !== row.orderProductId
    );
    producePieceList.value = producePieceList.value.filter(
      (item) => item.orderProductId !== row.orderProductId
    );
    // 汇总纸张的总令数
    mergeTotal(producePaperList.value, producePrintList.value);
    proxy.$modal.msgSuccess("删除成功");
  });
};
const findTechnologyList = (printType, sheet) => {
  // const resp = list.filter(item => item.name.includes('内文-'))
  if (printType == 1) {
    if (Number(sheet) < 1) {
      return "1796079690537132033";
    } else {
      return "1777324124657864705";
    }
  } else {
    return "1777324226373931009";
  }
};

function findMatchingCoefficient(row, workshopId) {
  if (!workshopId || row.packageType != 2) {
    return undefined;
  }

  const matchingCoefficient = coefficientList.value.find(
    (obj) =>
      obj.longWide == row.longWide &&
      obj.weight == row.weight &&
      obj.workshopId == workshopId
  );

  if (matchingCoefficient) {
    return matchingCoefficient.tonnageCoefficient;
  }

  return undefined;
}

// 选中的纸张编码
const changePaperData = (row) => {
  if (!producePaperList.value.some((item) => item.paperNo === row.paperNo)) {
    row.paperInfoId = row.id;
    row.type = row.material?.toString();
    row.selectPid = selectPid.value;
    row.paperNo = row.code;
    row.paperName = row.name;
    row.printType = row.packageType?.toString(); // 印刷方式
    // if (row.printType == 1) {
    //   // //如果是平张印刷，损耗系数=0.123，如果是轮转印刷，损耗系数=0.365
    //   row.lossCoefficient = 0.123;
    // } else {
    //   row.lossCoefficient = 0.365;
    // }
    row.specifications = row.specs;
    row.paperSpecifications = row.specs;
    row.length = row.longWide;
    row.width = row.wide;
    row.unitPrice = row.authorityPrice;
    row.amount = row.quantity;
    row.orderProductId = selectPid.value;
    row.createTime = undefined;
    producePaperList.value.push(row);
    const resp = produceProductList.value.every((item) => !item.paperNo);
    // resp 有没有选中的纸张编码
    if (resp) {
      produceProductList.value.forEach((item) => {
        // item.paperType = row.paperType
        item.paperNo = row.code;
        item.paperName = row.name;
      });
      producePrintList.value.forEach((ele, index) => {
        // 获取吨位系数
        ele.tonnageCoefficient = findMatchingCoefficient(
          row,
          form.value.workshopId
        );
        ele.paperSpecifications = row.specs;
        ele.paperNo = row.code;
        ele.paperName = row.name;
        ele.weight = row.weight;
        ele.paperType = row.paperType;
        ele.clothWidth = row.longWide;
        ele.printType = row.packageType?.toString(); // 印刷方式
        ele.technologyId = findTechnologyList(ele.printType, ele.sheet);
        ele.brand = row.brand;
        // 损耗系数啊
        if (row.packageType == 1) {
          getCoefficientP(ele.sheetSize, ele.printColour, ele.printAmount).then(
            (res) => {
              if (ele.printAmount < 1000) {
                // 另行加放
                // 平张：印数<1000的时候，另行加放为印张*80/1000
                ele.lxjf = toNumber(((ele.sheet || 0) * 80) / 1000, 4);
              } else {
                ele.lxjf = undefined;
              }
              ele.lossCoefficient = res;
              changeLossCoefficient(ele, index);
            }
          );
        } else {
          getCoefficientJ(
            ele.sheetSize,
            form.value.workshopId,
            ele.printAmount
          ).then((res) => {
            ele.lossCoefficient = res;
            changeLossCoefficient(ele, index);
          });
        }
        //20240326 提交的时候自动分配机台
        // if (ele.sheetSize) {
        //     changeWorkBranch(ele, index).then((res) => {
        //         if (ele.printType == 2) {
        //             if (Number(ele.sheet) % 1 === 0.5 && Number(ele.sheet) !== 0.5) {
        //                 handleHalfAutomatic(ele)
        //             }
        //         }
        //     })
        // }
      });
    } else {
      // 单个切换纸张
      let executedOnce = false;
      producePrintList.value.forEach((ele, index) => {
        if (ele.orderProductId === row.selectPid) {
          // 当前印刷切换的纸
          if (route.query.id) {
            // if (ele.printType != row.packageType && !executedOnce) {
            //   handleDeleteTsBack(ele);
            //   executedOnce = true;
            // }
            if (row.packageType == 2 && !executedOnce) {
              console.log(11);
              handleDeleteTsBack(ele);
              executedOnce = true;
            }
          }
          console.log(22);
          nextTick(() => {
            ele.tonnageCoefficient = findMatchingCoefficient(
              row,
              form.value.workshopId
            );
            ele.paperSpecifications = row.specs;
            // ele.tonnageCoefficient = row.tonnageCoefficient ? row.tonnageCoefficient : 1 //吨位系数
            ele.paperNo = row.code;
            ele.paperName = row.name;
            ele.weight = row.weight;
            ele.paperType = row.paperType;
            ele.printType = row.packageType?.toString(); // 印刷方式
            ele.technologyId = findTechnologyList(ele.printType, ele.sheet);
            ele.clothWidth = row.longWide;
            ele.brand = row.brand;
            ele.isQk = "1";
            // 损耗系数啊
            if (row.packageType == 1) {
              getCoefficientP(
                ele.sheetSize,
                ele.printColour,
                ele.printAmount
              ).then((res) => {
                // // 损耗系数+轮转吨数清空
                ele.tonnageCoefficient = undefined;
                ele.rotateTon = undefined;
                // ele.lxjf= undefined
                if (ele.printAmount < 1000) {
                  // 另行加放
                  // 平张：印数<1000的时候，另行加放为印张*80/1000
                  ele.lxjf = toNumber(((ele.sheet || 0) * 80) / 1000, 4);
                } else {
                  ele.lxjf = undefined;
                }
                ele.lossCoefficient = res;
                changeLossCoefficient(ele, index);
              });
            } else {
              getCoefficientJ(
                ele.sheetSize,
                form.value.workshopId,
                ele.printAmount
              ).then((res) => {
                ele.lxjf = undefined;
                ele.lossCoefficient = res;
                changeLossCoefficient(ele, index);
              });
            }

            //20240326提交之后自动分配机台
            // if (ele.sheetSize) {
            //     changeWorkBranch(ele, index).then((res) => {
            //         if (ele.printType == 2) {
            //             if (
            //                 Number(ele.sheet) % 1 === 0.5 &&
            //                 Number(ele.sheet) !== 0.5
            //             ) {
            //                 nextTick(() => {
            //                     handleHalfAutomatic(ele)
            //                 })
            //             }
            //         }
            //     })
            // }
          });
        }
      });
    }
  }
  produceProductList.value[paperIndex.value].paperNo = row.code;
  produceProductList.value[paperIndex.value].paperName = row.name;
  produceProductList.value[paperIndex.value].paperType = row.paperType;
  producePaperList.value = filterArr(
    produceProductList.value,
    producePaperList.value
  );
  nextTick(() => {
    mergeTotal(producePaperList.value, producePrintList.value);
    handleProducePiece();
  });
  paperOpen.value = false;
};
function filterArr(list, arr) {
  const uniqueArr = arr.filter((item, index, self) => {
    return (
      self.findIndex((elem) => elem.paperNo === item.paperNo) === index &&
      list.some((elem) => elem.paperNo === item.paperNo)
    );
  });
  return uniqueArr;
}

const changeBCCC = (row, index) => {
  // 损耗系数啊
  producePrintList.value.forEach((item, index) => {
    if (row.orderProductId == item.orderProductId) {
      item.sheetSize = row.sheetSize;
      if (item.printType == 1) {
        getCoefficientP(
          item.sheetSize,
          item.printColour,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      } else {
        getCoefficientJ(
          item.sheetSize,
          form.value.workshopId,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      }
      //先把印刷管理中的吨位系数置空
      //调用获取吨位系数

      // if (
      //     producePaperList != null &&
      //     producePaperList.value.length > 0 &&
      //     form.value.workshopId != undefined
      // ) {
      //     getPaperTonByParams({
      //         paperId: producePaperList.value[0].paperInfoId,
      //         workshopName: form.value.workshopId,
      //         sheetSize: item.sheetSize,
      //     }).then(res => {
      //         if (res && res.rows.length > 0) {
      //             item.tonnageCoefficient = res.rows[0].tonFactor ? res.rows[0].tonFactor : 1
      //             item.rotateTon = toNumber(
      //                 (Number(item.totalReamAmount) || 0) /
      //                     (Number(item.tonnageCoefficient) || 0),
      //                 4
      //             )
      //         } else {
      //             item.tonnageCoefficient = 1
      //         }
      //     })
      // }
    }
  });
};
function findWorkMatchingCoefficient(row, workshopId) {
  if (!row.printType || row.printType != 2) {
    return undefined;
  }

  const matchingCoefficient = coefficientList.value.find(
    (obj) =>
      obj.clothWidth == row.longWide &&
      obj.weight == row.weight &&
      obj.workshopId == workshopId
  );

  if (matchingCoefficient) {
    return matchingCoefficient.tonnageCoefficient;
  }

  return undefined;
}

//车间
const changeWorkShopName = (row) => {
  ems_workshop.value.forEach((item) => {
    if (row == item.value) {
      form.value.workshopName = item.label;
    }
  });
  if (producePrintList.value) {
    producePrintList.value.forEach((item, index) => {
      nextTick(() => {
        item.tonnageCoefficient = findWorkMatchingCoefficient(item, row);
      });
      if (item.printType == 1) {
        getCoefficientP(
          item.sheetSize,
          item.printColour,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      } else {
        getCoefficientJ(
          item.sheetSize,
          form.value.workshopId,
          item.printAmount
        ).then((res) => {
          item.lossCoefficient = res;
          changeLossCoefficient(item, index);
        });
      }
    });
  }

  // if (producePaperList != null && producePaperList.value.length > 0) {
  //     //先把印刷管理中的吨位系数置空
  //     producePrintList.value.forEach((item, index) => {
  //         item.tonnageCoefficient = 1
  //     })

  //     //获取吨位系数
  //     getPaperTonByParams({
  //         paperId: producePaperList.value[0].paperInfoId,
  //         workshopName: form.value.workshopId,
  //     }).then(res => {
  //         if (res && res.rows.length > 0) {
  //             produceProductList.value.forEach((productItem, index) => {
  //                 res.rows.forEach((tonItem, inde) => {
  //                     if (productItem.sheetSize == tonItem.sheetSize) {
  //                         //  1.获取纸张里面的版材尺寸 producePaperList
  //                         producePrintList.value.forEach((item, index) => {
  //                             if (
  //                                 productItem.orderProductId == item.orderProductId &&
  //                                 productItem.sheetSize == item.sheetSize
  //                             ) {
  //                                 item.tonnageCoefficient = tonItem.tonFactor
  //                                     ? tonItem.tonFactor
  //                                     : 1
  //                                 item.rotateTon = toNumber(
  //                                     (Number(item.totalReamAmount) || 0) /
  //                                     (Number(item.tonnageCoefficient) || 0),
  //                                     4
  //                                 )
  //                             }
  //                         })
  //                     }
  //                 })
  //             })
  //         }
  //     })
  // }
};

// 选择板材尺寸 分配机台
const changeWorkBranch = (row, index) => {
  return new Promise((resolve, reject) => {
    if (!row.printType) {
      // produceProductList.value[index].sheetSize = undefined;
      // producePrintList.value[index].sheetSize = undefined;
      resolve();
      return;
      // return ElMessage({
      //   message: "请选择纸张",
      //   type: "warning",
      // });
    }
    // printType // 印刷方式
    getWorkBench({ model: row.printType, size: row.sheetSize }).then((res) => {
      if (res.rows.length > 0) {
        producePrintList.value[index].machineId = res.rows[0].pid;
        producePrintList.value[index].machineName = res.rows[0].machineName;
        producePrintList.value[index].workshopName = res.rows[0].workshopName;
        // ems_machine_info_waste_rate  损耗比例
        const rate = ems_machine_info_waste_rate.value.filter(
          (item) => item.value == res.rows[0].wasteRate
        )[0].label;
        producePrintList.value[index].lossCoefficient = Number(rate);
        producePrintList.value[index].lossReam = toNumber(
          Number(rate) * Number(row.reamAmount),
          4
        );
        producePrintList.value[index].totalReamAmount = toNumber(
          Number(rate) * Number(row.reamAmount) + Number(row.reamAmount),
          4
        );
        // 轮转吨数 轮转吨数=用纸总令数 / 吨位系数
        producePrintList.value[index].rotateTon = toNumber(
          Number(producePrintList.value[index].totalReamAmount || 0) /
            Number(producePrintList.value[index].tonnageCoefficient || 1),
          4
        );

        if (row.printAmount) {
          getputratio({
            machineId: res.rows[0].pid,
            orderNum: row.printAmount,
          }).then((resp) => {
            if (resp || resp == 0) {
              producePrintList.value[index].lxjf = resp;
              //下单印数 = 印数+另行加放
              producePrintList.value[index].orderPrintCount =
                Number(resp) +
                Number(producePrintList.value[index].printAmount);
              mergeTotal(producePaperList.value, producePrintList.value);
            }
          });
          resolve();
        } else {
          mergeTotal(producePaperList.value, producePrintList.value);
          resolve();
        }
        // 汇总纸张的总令数
      } else {
        // produceProductList.value[index].sheetSize = undefined;
        // producePrintList.value[index].sheetSize = undefined;
        ElMessage({
          message: "未找到匹配的机台,请去设备/机台管理维护",
          type: "warning",
        });
        resolve();
      }
    });
  });
};
// 累加
const mergeTotal = async (list, arr) => {
  list.forEach((item) => {
    // arr 是 印刷
    item.reamAmount = 0;
    arr.forEach((obj) => {
      if (obj.printType == 1) {
        // 平张 如果是平张，数量汇总=用纸总令数
        if (obj.lossCoefficient) {
          obj.lossReam = toNumber(
            obj.lossCoefficient * Number(obj.reamAmount || 0),
            4
          );
          obj.totalReamAmount = toNumber(
            obj.lossCoefficient * Number(obj.reamAmount || 0) +
              Number(obj.reamAmount || 0),
            4
          );
        }
        if (item.paperNo == obj.paperNo) {
          item.reamAmount +=
            Number(obj.totalReamAmount || 0) + Number(obj.lxjf || 0);
        }
      } else if (obj.printType == 2) {
        // 卷筒  如果是轮转，数量汇总=轮转吨数+另行加放 轮转吨数=用纸总令数/吨位系数
        if (item.paperNo == obj.paperNo) {
          item.reamAmount += Number(obj.rotateTon || 0) + Number(obj.lxjf || 0);
        }
      }
    });
    if (item.reamAmount) {
      item.reamAmount = toNumber(item.reamAmount, 4);
      // item.price = toNumber((Number(item.unitPrice) || 0) * item.reamAmount, 2)
    }
  });
};

// 清除主键
const clearId = (list, key) => {
  list.forEach((item) => {
    delete item[key];
  });
};

const createdId = (list) => {
  const idMap = new Map(); // 用于存储原始 printId 和新生成的 printId 的映射关系

  list.forEach((item) => {
    const newPrintId = uuidv4();
    idMap.set(item.printId, newPrintId);
    item.printId = newPrintId;
  });

  list.forEach((item) => {
    const { printPid } = item;
    if (printPid && idMap.has(printPid)) {
      item.printPid = idMap.get(printPid);
    }
  });
};

// 生成贴数
const handleProducePiece = () => {
  producePieceList.value = [];
  const list = [];
  producePrintList.value.forEach((item) => {
    if (Number(item.sheet) > 1 && item.lxjf) {
      item.currentLxjf = toNumber(Number(item.lxjf) / Number(item.sheet), 4);
    }
    if (!item.status) {
      for (let i = 0; i < Math.ceil(item.sheet); i++) {
        list.push({
          ...item,
          sheet: item.sheet < 1 ? item.sheet : 1,
          lxjf: item.currentLxjf ? item.currentLxjf : undefined,
        });
      }
    } else {
      list.push({ ...item, sheet: item.sheet });
    }
  });
  producePieceList.value = generateList(list);
};

// 修改
const editProduceInfo = () => {
  form.value.irregularBooks = JSON.stringify({
    bookCode: bookCode.value,
    listBPT: listBPT.value,
  });
  editProduce({
    ...form.value,
    produceProductList: produceProductList.value,
    producePaperList: producePaperList.value,
    producePrintList: producePrintList.value,
    producePieceList: producePieceList.value,
  }).then((res) => {
    ElMessage({
      message: "修改成功",
      type: "success",
    });
  });
};
const submitForm = async () => {
  try {
    form.value.irregularBooks = JSON.stringify({
      bookCode: bookCode.value,
      listBPT: listBPT.value,
    });
    await userRef.value.validate();
    await produceProductListForm.value.validate();
    // await producePaperListForm.value.validate();
    await producePrintListForm.value.validate();
    if (route.query?.id) {
      if (copy.value) {
        // 复制
        form.value.status = 1;
        form.value.produceId = undefined;
        clearId(produceProductList.value, "productId");
        clearId(producePaperList.value, "paperId");
        clearId(producePieceList.value, "pieceId");
        if (producePieceList.value.length < 1) {
          handleProducePiece();
        }
        await addProduceOrderList({
          ...form.value,
          processStatus: "1",
          isSuspend: "",
          makeStatus: "1",
          produceProductList: produceProductList.value,
          producePaperList: producePaperList.value,
          producePrintList: producePrintList.value,
          producePieceList: producePieceList.value,
        });
        ElMessage({
          message: "复制成功",
          type: "success",
        });
      } else {
        await addProduceOrderList({
          ...form.value,
          produceProductList: produceProductList.value,
          producePaperList: producePaperList.value,
          producePrintList: producePrintList.value,
          producePieceList: producePieceList.value,
        });
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
      }
      goBack();
    } else {
      // 新增
      if (producePieceList.value.length < 1) {
        handleProducePiece();
      }
      form.value.status = 1;
      await addProduceOrderList({
        ...form.value,
        produceProductList: produceProductList.value,
        producePaperList: producePaperList.value,
        producePrintList: producePrintList.value,
        producePieceList: producePieceList.value,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    if (Object.keys(error)?.join(",").includes(".")) {
      const errInfoList = Object.values(error);
      const err = [];
      errInfoList.forEach((item) => {
        err.push(item[0].message);
      });
      ElMessage({
        message: `请将${err.join("、")}信息补充完整`,
        type: "warning",
      });
    }
  }
};

function handleGroup(arr) {
  const obj = {};
  const groups = [];
  arr.forEach((item) => {
    if (!obj[item.orderProductId]) {
      // 根据id分组
      groups.push({
        groupName: item.orderProductId,
        items: [item],
      });
      obj[item.orderProductId] = item;
    } else {
      groups.find((v) => {
        // 选择符合条件的第一个元素
        if (v.groupName === item.orderProductId) {
          v.items.push(item);
        }
      });
    }
  });
  return groups;
}

function sortByIndex(arr) {
  return arr.sort((a, b) => {
    if (a.labeling === undefined) {
      return 1; // 将没有 index 的对象排在后面
    } else if (b.labeling === undefined) {
      return -1; // 将没有 index 的对象排在后面
    } else {
      return a.labeling - b.labeling; // 按 index 排序
    }
  });
}
function moveElementByIndex(data, dataList, index) {
  // 找到具有特定 index 的元素
  let targetElement = null;
  for (let i = 0; i < data.length; i++) {
    if (data[i].labeling && data[i].labeling === index) {
      targetElement = data[i];
      break;
    }
  }
  if (targetElement) {
    dataList.splice(index - 1, 0, targetElement);
  }
  return data;
}
function generateList(arr) {
  const list = handleGroup(arr);
  for (let k in list) {
    const res = sortByIndex(list[k].items);
    list[k].items = [];
    res.forEach((obj) => {
      // 如果印色是2+2，默认双色单道，如果是其他，默认单色双道
      if (obj.printColour == 4) {
        obj.wagesType = "双色单道"; //"1";
      } else {
        obj.wagesType = "单色双道"; // "2";
      }
      if (!obj.labeling) {
        list[k].items.push(obj);
      }
    });
    res.forEach((item, INDEX) => {
      if (item.hasOwnProperty("labeling")) {
        moveElementByIndex(res, list[k].items, item.labeling);
      }
    });
  }
  const resp = [];
  for (let k in list) {
    list[k].items.forEach((ele, index) => {
      ele.pieceView = index + 1;
      resp.push(ele);
    });
  }
  return resp;
}
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}

.text {
  font-weight: 600;
  color: #666262;
}

table,
th,
td {
  border: 1px solid #ccc;
}

th,
td {
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}

.myTable {
  overflow: auto;
  /* 或者使用 scroll */
  white-space: nowrap;
  width: 100%;
}
</style>
